package com.hst.capacity.application.biz.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.smartravel.map.baidu.RouteMatrix;
import cn.smartravel.map.qq.WeMapTemplate;
import cn.smartravel.map.qq.response.GeoCoderLocationVO;
import cn.smartravel.map.qq.response.geocoder.ResultLocation;
import cn.smartravel.traffic.alitrip.AlitripCarOpen;
import cn.smartravel.traffic.usoft17.RideSupplierCallback;
import cn.smartravel.traffic.usoft17.model.request.callback.OrderStatusDTO;
import cn.smartravel.traffic.usoft17.model.response.callback.ResultVO;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.hst.capacity.application.biz.*;
import com.hst.capacity.application.fence.biz.FenceBiz;
import com.hst.capacity.application.jpush.service.JPushService;
import com.hst.capacity.domain.common.constants.*;
import com.hst.capacity.domain.exception.BusinessException;
import com.hst.capacity.domain.model.entity.account.SpecialDriverAccountDetailEntity;
import com.hst.capacity.domain.model.entity.driver.DriverEntity;
import com.hst.capacity.domain.model.entity.franchisee.commision.FranchiseeCommisionEntity;
import com.hst.capacity.domain.model.entity.member.MemberEntity;
import com.hst.capacity.domain.model.entity.order.job.JobPlatformEntity;
import com.hst.capacity.domain.model.entity.order.pool.OrderPoolEntity;
import com.hst.capacity.domain.model.entity.order.specialcar.*;
import com.hst.capacity.domain.model.entity.setting.airport.AirportEntity;
import com.hst.capacity.domain.model.entity.setting.airport.AirportScopeEntity;
import com.hst.capacity.domain.model.entity.setting.price.*;
import com.hst.capacity.domain.model.entity.setting.railway.RailwayEntity;
import com.hst.capacity.domain.model.entity.vehicle.VehicleEntity;
import com.hst.capacity.domain.model.request.OrderParam;
import com.hst.capacity.domain.model.request.dispatch.DispatchDriverParam;
import com.hst.capacity.domain.model.request.dispatch.DispatchParam;
import com.hst.capacity.domain.model.request.dispatcher.DispatcherSearchOrderParam;
import com.hst.capacity.domain.model.request.orderpool.OrderPoolAiParam;
import com.hst.capacity.domain.model.request.orderpool.OrderPoolParam;
import com.hst.capacity.domain.model.request.price.OrderPoolPriceParam;
import com.hst.capacity.domain.model.request.specialcar.SpCarSettlementViewListParam;
import com.hst.capacity.domain.model.request.specialcar.SpListParam;
import com.hst.capacity.domain.model.request.specialcar.SpOrderDestroyParam;
import com.hst.capacity.domain.model.request.system.SystemAlertParam;
import com.hst.capacity.domain.model.response.PagingResultVO;
import com.hst.capacity.domain.model.response.driver.DriverInfoVO;
import com.hst.capacity.domain.model.response.order.OrderBillInfoVO;
import com.hst.capacity.domain.model.response.order.OrderPoolVO;
import com.hst.capacity.domain.model.response.order.OrderPriceVO;
import com.hst.capacity.domain.model.response.order.OrderVO;
import com.hst.capacity.domain.model.response.setting.RouteVO;
import com.hst.capacity.domain.model.response.setting.price.pojo.*;
import com.hst.capacity.domain.model.response.specialcar.SpDetailVO;
import com.hst.capacity.domain.model.response.specialcar.SpSettlementViewVO;
import com.hst.capacity.domain.repository.redis.RouteRedis;
import com.hst.capacity.domain.service.*;
import com.hst.capacity.infra.convertor.*;
import com.hst.capacity.infra.persistence.jpa.account.SpecialDriverAccountDetailRepository;
import com.hst.capacity.infra.persistence.jpa.driver.DriverProfileRepository;
import com.hst.capacity.infra.persistence.jpa.driver.DriverRepository;
import com.hst.capacity.infra.persistence.jpa.franchisee.customer.CustomerFranchiseeRepository;
import com.hst.capacity.infra.persistence.jpa.order.pool.OrderPoolRepository;
import com.hst.capacity.infra.persistence.jpa.order.specialcar.*;
import com.hst.capacity.infra.persistence.jpa.setting.commision.FranchiseeCommisionRepository;
import com.hst.capacity.infra.persistence.jpa.setting.price.*;
import com.hst.capacity.infra.persistence.jpa.setting.station.AirportRepository;
import com.hst.capacity.infra.persistence.jpa.setting.station.AirportScopeRepository;
import com.hst.capacity.infra.persistence.jpa.setting.station.RailStationRepository;
import com.hst.capacity.infra.persistence.jpa.vehicle.VehicleRepository;
import com.hst.capacity.infra.persistence.jpa.vehicle.VehicleTypeRepository;
import com.hst.capacity.infra.persistence.mybatis.OrderPoolMapper;
import com.hst.capacity.infra.util.DateUtil;
import com.hst.capacity.infra.util.StringUtil;
import com.taobao.api.ApiException;
import com.taobao.api.request.AlitripCarOrderConfirmRequest;
import com.taobao.api.response.AlitripCarOrderConfirmResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@Service
public class OrderPoolBizImpl implements OrderPoolBiz {

    @Autowired
    DriverService driverService;
    @Autowired
    VehicleService vehicleService;
    @Autowired
    MemberService memberService;
    @Autowired
    OrderPoolService orderService;
    @Autowired
    AuthService authService;
    @Autowired
    OrderPoolMapper orderMapper;
    @Autowired
    JPushService jPushService;

    @Autowired
    JobPlatformBiz jobPlatformBiz;
    @Autowired
    SmsBiz smsBiz;
    @Autowired
    VehicleBiz vehicleBiz;
    @Autowired
    FranchiseeBiz franchiseeBiz;
    @Autowired
    DingTalkBiz dingTalkBiz;
    @Autowired
    FenceBiz fenceBiz;

    @Autowired
    AirportRepository airportRepository;
    @Autowired
    AirportScopeRepository airportScopeRepository;
    @Autowired
    RailStationRepository railStationRepository;
    @Autowired
    SpOrderSettlementRepository orderSettlementRepository;
    @Autowired
    SpecialDriverAccountDetailRepository accountDetailRepository;
    @Autowired
    SpOrderDestroyRepository destroyRepository;
    @Autowired
    SpOrderDispatchRepository dispatchRepository;
    @Autowired
    SpCarOrderCancelHistoryRepository spOrderCancelHistoryRepository;
    @Autowired
    CustomerFranchiseeRepository customerFranchiseeRepository;
    @Autowired
    VehicleRepository vehicleRepository;
    @Autowired
    DriverRepository driverRepository;
    @Autowired
    DriverProfileRepository driverProfileRepository;
    @Autowired
    OrderPoolRepository orderRepository;
    @Autowired
    AirportPriceEntityRepository airportPriceRepository;
    @Autowired
    RailwayStationPriceRepository railwayPriceRepository;
    @Autowired
    NewAirportPriceRepository newAirportPriceRepository;
    @Autowired
    NewStationPriceRepository newStationPriceRepository;
    @Autowired
    AirportCommonPriceRepository airportCommonPriceRepository;
    @Autowired
    StationCommonPriceRepository stationCommonPriceRepository;
    @Autowired
    SpPremiumPriceRepository spPremiumPriceRepository;
    @Autowired
    VehicleTypeRepository vehicleTypeRepository;
    @Autowired
    SpCarOrderOperationHistoryRepository orderOperationHistoryRepository;
    @Autowired
    SpOrderStatusHistoryRepository orderStatusHistoryRepository;
    @Autowired
    SpCarOrderCancelHistoryRepository orderCancelHistoryRepository;
    @Autowired
    SpCarOrderHistoryRepository SpCarOrderHistoryRepository;
    @Autowired
    FranchiseeCommisionRepository franchiseeCommisionRepository;
    @Autowired
    FranchiseeCommisionRepository fcRepository;

    @Autowired
    RouteMatrix routeMatrix;
    @Autowired
    WeMapTemplate weMapTemplate;
    @Autowired
    RouteRedis routeRedis;
    @Autowired
    AlitripCarOpen alitripCarOpen;
    @Autowired
    RideSupplierCallback callback;

//    /**
//     * 获取站点以及快车价格
//     * @param origins
//     * @param destinations
//     * @return
//     */
//    @Override
//    public RouteVO calOrderDistance(int coordinateType, String origins, String destinations) {
//        //TODO 放在REDIS里面 KEY为origins+destinations
//        String key = String.format("%s-%s", origins, destinations);
//        RouteVO vo = routeRedis.getRouteValue(key);
//        if (vo == null) {
//            vo = new RouteVO();
//            if (coordinateType == AliTripTransferConstants.CoordinateType.get(Constants.GeoMapType.GCJ02)) {
//                DistanceMatrixVO rm = weMapTemplate.matrix().matrixDriving(origins, destinations);
//                log.info("DistanceMatrixVO:"+JSON.toJSONString(rm));
//                if (rm.getStatus() != 0)
//                    return null;
//
//                vo.setDistance(rm.getDistanceValue());
//                vo.setSpendTime(rm.getDurationValue());
//            } else {
//                RouteMatrixVO rm = routeMatrix.getDriving(origins, destinations);
//                if (rm.getStatus() != 0)
//                    return null;
//
//                vo.setDistance(rm.getDistanceValue());
//                vo.setSpendTime(rm.getDurationValue());
//            }
//            routeRedis.writeRouteValue(key, vo);
//        }
//
//        return vo;
//    }

    @Override
    public OrderVO refresh(OrderParam param) {
        return OrderConvertor.INSTANCE.orderPoolToView(this.refresh(param.getIdOrder()));
    }

    private OrderPoolEntity refresh(String idOrder) {
        OrderPoolEntity entity = orderRepository.findByIdOrder(idOrder);
        return this.refresh(entity);
    }

    private OrderPoolEntity refresh(OrderPoolEntity entity) {
        try {
            if (entity.getOrderSource() == Constants.OrderSource.ALITRIP) {
//                AlitripCarOrderQueryRequest carOrderQueryRequest = new AlitripCarOrderQueryRequest();
//                carOrderQueryRequest.setOrderId(entity.getExternalOrderId());
//                AlitripCarOrderQueryResponse res = alitripCarOpen.orderQuery(carOrderQueryRequest);
//                if (res == null || res.getMessage() == null
//                        || !(res.getMessage().equals("成功") || res.getMessage().toLowerCase(Locale.ROOT).equals("ok")))
//                    throw new BusinessException(5002, "飞猪响应失败，未同步到订单状态，请联系管理员。");
//
//                log.info("获取飞猪订单状态" + JSON.toJSONString(res.getFirstResult()));
//                Long flyPigOrderStatus = res.getFirstResult().getStatus();
//                int status = AliTripTransferConstants.AliTripOrderStatus.get(flyPigOrderStatus);
//
//                if (status != entity.getStatus()) {
//                    log.info("更新订单状态" + entity.getStatus());
//                    if (status == Constants.OrderStatus.ORDER_STATUS_CANCEL) {
//                        entity.setStatus(status);
//                        entity = orderRepository.saveAndFlush(entity);
//                    }
//
//                    if (status == Constants.OrderStatus.ORDER_STATUS_CANCEL) {
//                        if (StringUtil.isNotBlank(entity.getIdDriver())) {
//                            DriverInfoVO driverInfoVO = driverService.driverInfo(entity.getIdDriver());
//                            smsBiz.sendCancelOrderSms(driverInfoVO.getDriverMobile(), entity.getAppointmentTime(), entity.getIdMember());
//                        }
//                    }
//                }
            }
        } catch (Exception e) {
        }
        return entity;
    }

    /**
     * 获取站点以及快车价格
     *
     * @param param
     * @return
     */
    @Override
    public OrderPriceVO getOrderPrice(OrderPoolPriceParam param) {

        RouteVO routeVO = routeRedis.calOrderDistance(
                param.getCoordinateType()
                , param.getOrigins(), param.getDestinations());

        if (routeVO == null)
            return null;

        param.setOrderDistance(routeVO.getDistance());
        param.setSpendTime(routeVO.getSpendTime());

        OrderPriceVO orderPrice = null;

        if (Constants.OrderBizType.Airport == param.getOrderBizType())
            orderPrice = calAirportOrderPrice(param);
        else if (Constants.OrderBizType.RailStation == param.getOrderBizType()) {
            log.info("执行计算接送站");
            orderPrice = calRailwayOrderPrice(param);
        }

        return orderPrice;
    }

    @Override
    public OrderPriceVO newOrderPoolPrice(OrderPoolPriceParam param, boolean isOrder) {
        HashMap<String, Object> reqParams = new HashMap<>();
        reqParams.put("policy","SHORT_DISTANCE,HIGHWAY_FIRST");
        RouteVO routeVO = routeRedis.calOrderDistance(
                param.getCoordinateType()
                , param.getOrigins(), param.getDestinations(), reqParams);

        if (routeVO == null) {
            if (!(param.getOrderDistance() > 0 && param.getSpendTime() > 0)) {
                return null;
            }
        } else {
            param.setOrderDistance(routeVO.getDistance());
            param.setSpendTime(routeVO.getSpendTime());
        }

        OrderPriceVO orderPrice = new OrderPriceVO();

        if (Constants.OrderBizType.Airport == param.getOrderBizType()) {
            log.info("执行计算新的接送机");
            //orderPrice = calNewAirportOrderPrice(param, isOrder);
            orderPrice = calNewAirportOrderPrice(param, isOrder);
        } else if (Constants.OrderBizType.RailStation == param.getOrderBizType()) {
            log.info("执行计算新的接送站");
            //orderPrice = calNewStationOrderPrice(param, isOrder);
            orderPrice = calNewStationOrderPrice(param, isOrder);
        }

        return orderPrice;
    }

    @Override
    public OrderPriceVO orderPoolCommonPrice(OrderPoolPriceParam param, boolean isOrder) {
        HashMap<String, Object> reqParams = new HashMap<>();
        reqParams.put("policy","SHORT_DISTANCE,HIGHWAY_FIRST");
        RouteVO routeVO = routeRedis.calOrderDistance(
                param.getCoordinateType()
                , param.getOrigins(), param.getDestinations(), reqParams);

        if (routeVO == null) {
            if (!(param.getOrderDistance() > 0 && param.getSpendTime() > 0)) {
                return null;
            }
        } else {
            param.setOrderDistance(routeVO.getDistance());
            param.setSpendTime(routeVO.getSpendTime());
        }

        OrderPriceVO orderPrice = new OrderPriceVO();

        if (Constants.OrderBizType.Airport == param.getOrderBizType()) {
            log.info("执行计算共通的接送机");
            orderPrice = calAirportCommonOrderPrice(param, isOrder);
        } else if (Constants.OrderBizType.RailStation == param.getOrderBizType()) {
            log.info("执行计算共通的接送站");
            orderPrice = calStationCommonOrderPrice(param, isOrder);
        }

        return orderPrice;
    }

    @Override
    public OrderPoolEntity savePoolOrder(OrderPoolParam param) {

        OrderPoolEntity order = null;
        boolean isCreate = true;
        if (StringUtil.isNotBlank(param.getIdOrder())) {
            order = orderRepository.findByIdOrder(param.getIdOrder());
            if (order == null)
                throw new BusinessException(5002, "订单不存在，请检查参数idOrder是否正确");
            order.setUpdateBy(Constants.Def_CreateBy);
            isCreate = false;
        }

        //1，乘客账户存在时，前端未传值的情况下，取得乘客信息放到对应参数当中
        String idMember = param.getIdMember();
        if (StringUtil.isBlank(param.getIdMember())) {
            MemberEntity member = memberService.createNewMember(param.getUserMobile());
            idMember = member.getIdMember();
        }

        //定价ID未知时，取得并保存
        OrderPoolPriceParam priceParam = new OrderPoolPriceParam();
        priceParam.setRegionCode(param.getRegionCode());
        StringBuilder origins = new StringBuilder(param.getStartAddressLatitude()).append(",").append(param.getStartAddressLongitude());
        StringBuilder destinations = new StringBuilder(param.getEndAddressLatitude()).append(",").append(param.getEndAddressLongitude());
        priceParam.setIdFranchisee(param.getIdFranchisee());
        priceParam.setOrigins(origins.toString());
        priceParam.setDestinations(destinations.toString());
        priceParam.setIdServiceType(param.getIdServiceType());
        priceParam.setIdVehicleType(param.getIdVehicleType());
        priceParam.setIdStation(param.getIdRailwayStation());
        priceParam.setIdRailwayStation(param.getIdRailwayStation());
        priceParam.setIdAirport(param.getIdAirport());
        priceParam.setOrderBizType(param.getOrderBizType());
        log.debug("priceParam信息：" + JSON.toJSONString(priceParam));
        //定价取得
        OrderPriceVO oprv = this.getOrderPrice(priceParam);

        if (oprv == null)
            throw new BusinessException(5001, "未取得定价信息");

        //创建订单
        if (isCreate) {
            //order = OrderPoolConvertor.INSTANCE.convert(param);
            order = new OrderPoolEntity();
            order.setIdOrder(StringUtil.createOrderID(0));
            order.setOrderType(Constants.OrderType.APPOINTMENT);
            order.setCarpoolType(Constants.OrderCarpoolType.Chartered);//拼车包车用这个]
            int status = (param.getStatus() == null) ? Constants.OrderStatus.ORDER_STATUS_CREATED : param.getStatus();
            order.setStatus(status);
            int paymentStatus = (param.getPaymentStatus() == null) ? Constants.PaymentStatus.UN_PAY : param.getPaymentStatus();
            order.setPaymentStatus(paymentStatus);
            int paymentRequitment = (param.getPaymentRequitment() == null) ? Constants.PaymentRequitment.IN_ADVANCE : param.getPaymentRequitment();
            order.setPaymentRequitment(paymentRequitment);
            int paymentType = (param.getPaymentType() == null) ? Constants.PaymentType.CASH : param.getPaymentType();
            order.setPaymentType(paymentType);
            order.setDivideAccountsStatus(Constants.DivideAccountsStatus.UN);
            order.setExternalOrderId(param.getExternalOrderId());
            order.setCreateBy(Constants.Def_CreateBy);
        }

        order.setIdMember(idMember);
        order.setIdFranchisee(param.getIdFranchisee());
        order.setIdServicePriceType(oprv.getIdServicePriceType());
        order.setIdServiceType(param.getIdServiceType());
        order.setIdVehicleType(param.getIdVehicleType());
        order.setIdTask(param.getIdTask());
        order.setRegionCode(param.getRegionCode());

        order.setIdStation(param.getIdRailwayStation());
        order.setIdAirport(param.getIdAirport());
        order.setUserName(param.getUserName());
        order.setUserMobile(param.getUserMobile());
        order.setPassengerName(param.getUserName());//传值下单用户名
        order.setPassengerMobile(param.getPassengerMobile());
        order.setPassengerNumber(param.getPassengerNumber());
        order.setAppointmentTime(DateUtil.parseLocalDateTime(param.getAppointmentTime()));
        order.setAssignTime(DateUtil.parseLocalDateTime(param.getAssignTime()));
        order.setDriverLongitude(param.getDriverLongitude());
        order.setDeptime(DateUtil.parseLocalDateTime(param.getDeptime()));
        order.setStartAddress(param.getStartAddress());
        order.setStartAddressLongitude(param.getStartAddressLongitude());
        order.setStartAddressLatitude(param.getStartAddressLatitude());
        order.setEndAddress(param.getEndAddress());
        order.setEndAddressLongitude(param.getEndAddressLongitude());
        order.setEndAddressLatitude(param.getEndAddressLatitude());
        order.setDesttime(DateUtil.parseLocalDateTime(param.getDesttime()));
        order.setDropOffArea(param.getDropOffArea());
        order.setDropOffAreaLongitude(param.getDropOffAreaLongitude());
        order.setDropOffAreaLatitude(param.getDropOffAreaLatitude());
        order.setOrderSource(param.getOrderSource());

        order.setReferenceDistance(oprv.getOrderDistance());
        order.setEstimatedTime(oprv.getSpendTime());
        order.setEstimatedMoney(oprv.getTotalPrice());
        order.setOrderMemo(param.getOrderMemo());
        order.setOrderPriority(0);
        order.setSubBizType(param.getSubBizType());

//        if (order.getOrderSource() == Constants.OrderSource.ALITRIP) {
//            float driverIncome =
//            order.setDriverIncome();
//        }

        order = orderRepository.save(order);

        //追加订单状态
        if (isCreate) {
            SpCarOrderStatusHistoryEntity orderStatus = new SpCarOrderStatusHistoryEntity();
            orderStatus.setIdOrder(order.getIdOrder());
            orderStatus.setStatus(order.getStatus());
            orderStatus.setCreateBy(Constants.Def_CreateBy);
            orderStatus.setMemo("运力商系统录入订单");
            orderStatusHistoryRepository.save(orderStatus);
        } else {
            //修改记录

        }

        return order;
    }

    @Override
    public OrderPoolEntity createAiPoolOrder(OrderPoolAiParam aiParam) {

        //创建订单
        OrderPoolParam param = OrderPoolConvertor.INSTANCE.convert(aiParam);

        switch (aiParam.getOrderBizTypePage()) {
            case 1://接机
                // 接送机
                param.setOrderBizType(Constants.OrderBizType.Airport);
                param.setIdServiceType(Constants.ServiceType.AIRPORT_PICK);
                // 接
                param.setInStation(Constants.InStationStatus.IN_STATION_STATUS_JIEZHAN);
                break;
            case 2://送机
                // 接送机
                param.setOrderBizType(Constants.OrderBizType.Airport);
                param.setIdServiceType(Constants.ServiceType.AIRPORT_SEND);
                // 送
                param.setInStation(Constants.InStationStatus.IN_STATION_STATUS_SONGZHAN);
                break;
            case 3://接站
                // 接送站
                param.setOrderBizType(Constants.OrderBizType.RailStation);
                param.setIdServiceType(Constants.ServiceType.STATION_PICK);
                // 接
                param.setInStation(Constants.InStationStatus.IN_STATION_STATUS_JIEZHAN);
                break;
            case 4://送站
                // 接送站
                param.setOrderBizType(Constants.OrderBizType.RailStation);
                param.setIdServiceType(Constants.ServiceType.STATION_DELIVERY);
                // 送
                param.setInStation(Constants.InStationStatus.IN_STATION_STATUS_SONGZHAN);
                break;
        }

        boolean isCreate = true;
        OrderPoolEntity order = orderRepository.findByExternalOrderId(param.getExternalOrderId());
        //根据外部订单号查找订单
        if (order != null) {
            order.setUpdateBy(Constants.Def_CreateBy);
            isCreate = false;
        }
//        if (StringUtil.isNotBlank(param.getIdOrder())) {
//            order = orderRepository.findByIdOrder(param.getIdOrder());
//            if (order == null)
//                throw new BusinessException(5002,"订单不存在，请检查参数idOrder是否正确");
//            order.setUpdateBy(Constants.Def_CreateBy);
//            isCreate = false;
//        }
//
//        if (isCreate==true) {
//
//        }

        //1，乘客账户存在时，前端未传值的情况下，取得乘客信息放到对应参数当中
        String idMember = param.getIdMember();
        if (StringUtil.isBlank(param.getIdMember())) {
            MemberEntity member = memberService.createNewMember(param.getUserMobile());
            idMember = member.getIdMember();
        }

        //定价ID未知时，取得并保存
        OrderPoolPriceParam priceParam = new OrderPoolPriceParam();
        priceParam.setRegionCode(param.getRegionCode());
        StringBuilder origins = new StringBuilder(param.getStartAddressLatitude()).append(",").append(param.getStartAddressLongitude());
        StringBuilder destinations = new StringBuilder(param.getEndAddressLatitude()).append(",").append(param.getEndAddressLongitude());
        priceParam.setIdFranchisee(param.getIdFranchisee());
        priceParam.setOrigins(origins.toString());
        priceParam.setDestinations(destinations.toString());
        priceParam.setIdServiceType(param.getIdServiceType());
        priceParam.setIdVehicleType(param.getIdVehicleType());

        // 飞机站
        AirportEntity air = null;
        if (param.getOrderBizType() == 0) {
            String airAddress = "";
            //送的时候
            if (param.getInStation() == Constants.InStationStatus.IN_STATION_STATUS_SONGZHAN) {
                airAddress = param.getEndAddress();
            }else{
                airAddress = param.getStartAddress();
            }

            String[] names = airAddress.split("机场");
            if (names.length > 0) {
                String airportName = names[0];
                List<AirportEntity> list = airportRepository.findByCityCode(param.getRegionCode());
                if (list != null) {
                    for (int i = 0; i < list.size(); i++) {
                        AirportEntity entity = list.get(i);
                        AirportScopeEntity scopeEntity = airportScopeRepository.findByIdAirport(entity.getIdAirport());
                        if (scopeEntity != null && scopeEntity.getAirportScope().contains(airportName)) {
                            air = entity;
                            break;
                        } else if (entity.getName().contains(airportName)) {
                            air = entity;
                            break;
                        }
                    }
                }
            } else {
                throw new BusinessException(5002, "未找到对应的机场");
            }

            if (air == null) {
                throw new BusinessException(5002, "未找到对应的机场");
            }

            priceParam.setIdAirport(air.getIdAirport());
        }

        // 高铁站
        RailwayEntity railwayStation = null;
        if (param.getOrderBizType() == 1) {
            String railAddress = "";
            // 送的时候
            if (param.getInStation() == Constants.InStationStatus.IN_STATION_STATUS_SONGZHAN) {
                railAddress = param.getEndAddress();
            }else{
                railAddress = param.getStartAddress();
            }

            List<RailwayEntity> list = railStationRepository.findByCityCode(param.getRegionCode());
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    RailwayEntity entity = list.get(i);
                    if (railAddress.contains(entity.getName())) {
                        railwayStation = entity;
                        break;
                    }
                }
            }

//            if (railwayStation == null) {
//                if (railAddress.length() >= 6) {
//                    railwayStation = getRailwayStation(param.getRegionCode(), railAddress.substring(0, 4));
//                } else if (railAddress.length() <= 6) {
//                    railwayStation = getRailwayStation(param.getRegionCode(), railAddress.substring(0, 2));
//                }
//            }
            if (railwayStation == null) {
                throw new BusinessException(5002, "未找到对应的火车站");
            }
            priceParam.setIdStation(railwayStation.getIdStation());
            priceParam.setIdRailwayStation(railwayStation.getIdStation());
        }

        priceParam.setCoordinateType(Constants.CoordinateType.GCJ02.intValue());
        priceParam.setOrderBizType(param.getOrderBizType());
        log.debug("priceParam信息：" + JSON.toJSONString(priceParam));

        //定价取得
        //OrderPriceVO oprv = this.newOrderPoolPrice(priceParam, true);
        OrderPriceVO oprv = this.orderPoolCommonPrice(priceParam, true);

        // todo 定价ID取得
//        if (oprv == null)
//            throw new BusinessException(5001,"未取得定价信息");

        //创建订单
        if (isCreate) {
            //order = OrderPoolConvertor.INSTANCE.convert(param);
            order = new OrderPoolEntity();
            order.setIdOrder(StringUtil.createOrderID(0));
            order.setOrderType(Constants.OrderType.APPOINTMENT);
            order.setCarpoolType(Constants.OrderCarpoolType.Chartered);//拼车包车用这个]
            int status = (param.getStatus() == null) ? Constants.OrderStatus.ORDER_STATUS_CREATED : param.getStatus();
            order.setStatus(status);
            int paymentStatus = (param.getPaymentStatus() == null) ? Constants.PaymentStatus.UN_PAY : param.getPaymentStatus();
            if (param.getOrderSource() == Constants.OrderSource.ALITRIP ||
                    param.getOrderSource() == Constants.OrderSource.XIAODUO ||
                        param.getOrderSource() == Constants.OrderSource.HUWO)
                paymentStatus = Constants.PaymentStatus.ON_PAY;
            order.setPaymentStatus(paymentStatus);
            int paymentRequitment = (param.getPaymentRequitment() == null) ? Constants.PaymentRequitment.IN_ADVANCE : param.getPaymentRequitment();
            order.setPaymentRequitment(paymentRequitment);
            order.setDivideAccountsStatus(Constants.DivideAccountsStatus.UN);
            order.setExternalOrderId(param.getExternalOrderId());
            order.setCreateBy(Constants.Def_CreateBy);
            order.setCreateTime(DateUtil.parseLocalDateTime(aiParam.getCreateTime()));
        }

        order.setIdMember(idMember);
        order.setIdFranchisee(param.getIdFranchisee());

        order.setIdServiceType(param.getIdServiceType());
        order.setIdVehicleType(param.getIdVehicleType());
        order.setIdTask(param.getIdTask());
        order.setRegionCode(param.getRegionCode());

        order.setUserName(param.getUserName());
        order.setUserMobile(param.getUserMobile());
        order.setPassengerName(param.getUserName());//传值下单用户名
        order.setPassengerMobile(param.getPassengerMobile());
        order.setPassengerNumber(param.getPassengerNumber());
        order.setAppointmentTime(DateUtil.parseLocalDateTime(param.getAppointmentTime()));
        //order.setAssignTime(DateUtil.parseLocalDateTime(param.getAssignTime()));
        order.setDriverLongitude(param.getDriverLongitude());
        //order.setDeptime(DateUtil.parseLocalDateTime(param.getDeptime()));
        if (param.getOrderBizType() == 0) {
            order.setIdAirport(air.getIdAirport());
            order.setFlightNo(param.getFlightNo());
        } else {
            order.setIdStation(railwayStation.getIdStation());
            order.setFlightNo(param.getFlightNo());
        }
        order.setStartAddress(param.getStartAddress());
        order.setStartAddressLongitude(param.getStartAddressLongitude());
        order.setStartAddressLatitude(param.getStartAddressLatitude());
        order.setEndAddress(param.getEndAddress());
        order.setEndAddressLongitude(param.getEndAddressLongitude());
        order.setEndAddressLatitude(param.getEndAddressLatitude());
        //order.setDesttime(DateUtil.parseLocalDateTime(param.getDesttime()));
        order.setDropOffArea(param.getDropOffArea());
        order.setDropOffAreaLongitude(param.getDropOffAreaLongitude());
        order.setDropOffAreaLatitude(param.getDropOffAreaLatitude());
        order.setOrderSource(param.getOrderSource());

        if (oprv == null) {
            order.setIdServicePriceType("0");
            order.setReferenceDistance(priceParam.getOrderDistance());
            order.setEstimatedTime(priceParam.getSpendTime());
            //order.setEstimatedMoney(oprv.getTotalPrice());
        } else {
            order.setIdServicePriceType(oprv.getIdServicePriceType());
            order.setReferenceDistance(oprv.getOrderDistance());
            order.setEstimatedTime(oprv.getSpendTime());
            //order.setEstimatedMoney(oprv.getTotalPrice());
        }

        if (param.getOrderMoney() != null && param.getOrderMoney() > 0)
            order.setOrderMoney(param.getOrderMoney());
        if (param.getPayMoney() != null && param.getPayMoney() > 0)
            order.setPayMoney(param.getPayMoney());
        order.setEstimatedMoney(param.getEstimatedMoney());
        order.setOrderMemo(param.getOrderMemo());

        if (param.getDriverIncome() == null || param.getDriverIncome().floatValue() == 0) {
            FranchiseeCommisionEntity franchiseeCommisionEntity = null;
            if (StringUtil.isNotBlank(param.getIdFranchisee()))
                franchiseeCommisionEntity = franchiseeCommisionRepository.findByChannelAndIdFranchiseeAndModuleType(
                Constants.Channel.ALITRIP, param.getIdFranchisee(), Constants.OrderModuleType.SPECIAL);
            float driverIncome = param.getEstimatedMoney() * 0.75f;
            if (franchiseeCommisionEntity != null) {
                driverIncome = param.getEstimatedMoney() * franchiseeCommisionEntity.getDriverRate() / 100;
            }
            order.setDriverIncome(driverIncome);
        } else {
            order.setDriverIncome(param.getDriverIncome());
        }

        order.setOrderPriority(0);
        //order.setCreateTime(DateUtil.parseLocalDateTime(aiParam.getCreateTime()));
        order.setSubBizType(param.getSubBizType());
        order = orderRepository.save(order);

        //追加订单状态
        if (isCreate) {
            SpCarOrderStatusHistoryEntity orderStatus = new SpCarOrderStatusHistoryEntity();
            orderStatus.setIdOrder(order.getIdOrder());
            orderStatus.setStatus(order.getStatus());
            orderStatus.setCreateBy(Constants.Def_CreateBy);
            orderStatus.setMemo("运力商系统录入订单");
            orderStatusHistoryRepository.save(orderStatus);
        } else {
            //修改记录

        }

        return order;
    }

    /**
     * 创建订单
     *
     * @param param
     * @return
     */
    @Override
    public OrderPoolEntity createPoolOrder(OrderPoolParam param) {

        //1，乘客账户存在时，前端未传值的情况下，取得乘客信息放到对应参数当中
        String idMember = param.getIdMember();
        if (StringUtil.isBlank(param.getIdMember())) {
            MemberEntity member = memberService.createNewMember(param.getUserMobile());
            idMember = member.getIdMember();
        }

        //定价ID未知时，取得并保存
        OrderPoolPriceParam priceParam = new OrderPoolPriceParam();
        priceParam.setRegionCode(param.getRegionCode());
        StringBuilder origins = new StringBuilder(param.getStartAddressLatitude()).append(",").append(param.getStartAddressLongitude());
        StringBuilder destinations = new StringBuilder(param.getEndAddressLatitude()).append(",").append(param.getEndAddressLongitude());
        priceParam.setIdFranchisee(param.getIdFranchisee());
        priceParam.setOrigins(origins.toString());
        priceParam.setDestinations(destinations.toString());
        priceParam.setIdServiceType(param.getIdServiceType());
        priceParam.setIdVehicleType(param.getIdVehicleType());
        priceParam.setIdStation(param.getIdRailwayStation());
        priceParam.setIdRailwayStation(param.getIdRailwayStation());
        priceParam.setIdAirport(param.getIdAirport());
        priceParam.setOrderBizType(param.getOrderBizType());
        priceParam.setCoordinateType(param.getCoordinateType());
        log.info("priceParam信息：" + JSON.toJSONString(priceParam));
        //定价取得
        OrderPriceVO oprv = this.getOrderPrice(priceParam);

        if (oprv == null)
            throw new BusinessException(5001, "未取得定价信息");

        OrderPoolEntity order = orderRepository.findByExternalOrderId(param.getExternalOrderId());
        //创建订单
        if (order == null) {
            //order = OrderPoolConvertor.INSTANCE.convert(param);
            order = new OrderPoolEntity();
            order.setIdOrder(StringUtil.createOrderID(0));
            order.setCreateBy(Constants.Def_CreateBy);
        }

        //todo 2023.04.06
//        order.setIdMember(member.getIdMember());
//        order.setIdServicePriceType(oprv.getIdServicePriceType());
//        order.setOrderType(Constants.OrderType.APPOINTMENT);
//        order.setCarpoolType(Constants.OrderCarpoolType.Chartered);//拼车包车用这个
//        order.setStatus(Constants.OrderStatus.ORDER_STATUS_CREATED);
//        order.setPaymentStatus(Constants.PaymentStatus.UN_PAY);
//        order.setDivideAccountsStatus(Constants.DivideAccountsStatus.UN);
//        order.setReferenceDistance(oprv.getOrderDistance());
//        order.setEstimatedTime(oprv.getSpendTime());
//        float money = oprv.getTotalPrice();
//        order.setEstimatedMoney(money);
//        order.setOrderPriority(0);
//        order.setExternalOrderId(param.getExternalOrderId());
//        order.setUpdateBy(Constants.Def_CreateBy);

        order.setIdMember(idMember);
        order.setIdFranchisee(param.getIdFranchisee());
        order.setIdServicePriceType(oprv.getIdServicePriceType());
        order.setIdServiceType(param.getIdServiceType());
        order.setIdVehicleType(param.getIdVehicleType());
        order.setIdTask(param.getIdTask());
        order.setRegionCode(param.getRegionCode());
        order.setOrderType(Constants.OrderType.APPOINTMENT);
        order.setCarpoolType(Constants.OrderCarpoolType.Chartered);//拼车包车用这个
        order.setIdStation(param.getIdRailwayStation());
        order.setIdAirport(param.getIdAirport());
        order.setUserName(param.getUserName());
        order.setUserMobile(param.getUserMobile());
        order.setPassengerName(param.getUserName());//传值下单用户名
        order.setPassengerMobile(param.getPassengerMobile());
        order.setPassengerNumber(param.getPassengerNumber());
        order.setAppointmentTime(DateUtil.parseLocalDateTime(param.getAppointmentTime()));
        if (null != param.getAssignTime())
            order.setAssignTime(DateUtil.parseLocalDateTime(param.getAssignTime()));
        order.setDriverLongitude(param.getDriverLongitude());
        if (null != param.getDeptime())
            order.setDeptime(DateUtil.parseLocalDateTime(param.getDeptime()));
        order.setStartAddress(param.getStartAddress());
        order.setStartAddressLongitude(param.getStartAddressLongitude());
        order.setStartAddressLatitude(param.getStartAddressLatitude());
        order.setEndAddress(param.getEndAddress());
        order.setEndAddressLongitude(param.getEndAddressLongitude());
        order.setEndAddressLatitude(param.getEndAddressLatitude());
        if (null != param.getDesttime())
            order.setDesttime(DateUtil.parseLocalDateTime(param.getDesttime()));
        order.setDropOffArea(param.getDropOffArea());
        order.setDropOffAreaLongitude(param.getDropOffAreaLongitude());
        order.setDropOffAreaLatitude(param.getDropOffAreaLatitude());
        order.setOrderSource(param.getOrderSource());
        order.setStatus(Constants.OrderStatus.ORDER_STATUS_CREATED);
        int paymentStatus = (param.getPaymentStatus() == null) ? Constants.PaymentStatus.UN_PAY : param.getPaymentStatus();
        order.setPaymentStatus(paymentStatus);
        int paymentRequitment = (param.getPaymentRequitment() == null) ? Constants.PaymentRequitment.IN_ADVANCE : param.getPaymentRequitment();
        order.setPaymentRequitment(paymentRequitment);
        order.setDivideAccountsStatus(Constants.DivideAccountsStatus.UN);
        order.setReferenceDistance(oprv.getOrderDistance());
        order.setEstimatedTime(oprv.getSpendTime());
        order.setEstimatedMoney(oprv.getTotalPrice());
        order.setOrderMoney(oprv.getTotalPrice());
        order.setOrderMemo(param.getOrderMemo());
        order.setOrderPriority(0);
        order.setExternalOrderId(param.getExternalOrderId());

        FranchiseeCommisionEntity franchiseeCommisionEntity = null;
        float driverRate = 0.75f;
        if (StringUtil.isNotBlank(order.getIdFranchisee()))
            franchiseeCommisionEntity = fcRepository.findByChannelAndIdFranchiseeAndModuleType(Constants.Channel.ALITRIP,
                    order.getIdFranchisee(), Constants.OrderModuleType.SPECIAL);
        if (franchiseeCommisionEntity != null) {
            driverRate =  franchiseeCommisionEntity.getDriverRate()/100;
            float driverIncome = order.getEstimatedMoney() * driverRate;
            order.setDriverIncome(driverIncome);
        }

        if (order.getOrderSource() == Constants.OrderSource.ALITRIP ||
                order.getOrderSource() == Constants.OrderSource.XIAODUO||
                    order.getOrderSource() == Constants.OrderSource.HUWO) {
            order.setPaymentStatus(Constants.PaymentStatus.ON_PAY);
            order.setOrderMoney(param.getOrderMoney());
            order.setPayMoney(param.getPayMoney());
            if (order.getOrderMoney() != null) {
                float driverIncome = order.getOrderMoney() * driverRate;
                order.setDriverIncome(driverIncome);
            } else {
                float driverIncome = order.getEstimatedMoney() * driverRate;
                order.setDriverIncome(driverIncome);
            }
        }

//        order = orderRepository.save(order);
        order = orderRepository.save(order);

        //追加订单状态
        SpCarOrderStatusHistoryEntity orderStatus = new SpCarOrderStatusHistoryEntity();
        orderStatus.setIdOrder(order.getIdOrder());
        orderStatus.setStatus(order.getStatus());
        orderStatus.setCreateBy(Constants.Def_CreateBy);
        orderStatus.setMemo("运力商系统录入订单");
        orderStatusHistoryRepository.save(orderStatus);

        return order;
    }

    /**
     * 创建订单
     *
     * @param param
     * @return
     */
    @Override
    public OrderPoolEntity createNewPoolOrder(OrderPoolParam param) {

        //1，乘客账户存在时，前端未传值的情况下，取得乘客信息放到对应参数当中
        String idMember = param.getIdMember();
        if (StringUtil.isBlank(param.getIdMember())) {
            MemberEntity member = memberService.createNewMember(param.getUserMobile());
            idMember = member.getIdMember();
        }

        //定价ID未知时，取得并保存
        OrderPoolPriceParam priceParam = new OrderPoolPriceParam();
        priceParam.setRegionCode(param.getRegionCode());
        StringBuilder origins = new StringBuilder(param.getStartAddressLatitude()).append(",").append(param.getStartAddressLongitude());
        StringBuilder destinations = new StringBuilder(param.getEndAddressLatitude()).append(",").append(param.getEndAddressLongitude());
        priceParam.setIdFranchisee(param.getIdFranchisee());
        priceParam.setOrigins(origins.toString());
        priceParam.setDestinations(destinations.toString());
        priceParam.setIdServiceType(param.getIdServiceType());
        priceParam.setIdVehicleType(param.getIdVehicleType());
        priceParam.setIdStation(param.getIdRailwayStation());
        priceParam.setIdRailwayStation(param.getIdRailwayStation());
        priceParam.setIdAirport(param.getIdAirport());
        priceParam.setOrderBizType(param.getOrderBizType());
        priceParam.setCoordinateType(param.getCoordinateType());
        priceParam.setChannel(param.getChannel());
        priceParam.setAppointTime(param.getAppointmentTime());
        priceParam.setCarpoolType(param.getCarpoolType());
        log.info("priceParam信息：" + JSON.toJSONString(priceParam));
        //定价取得
        OrderPriceVO oprv = this.newOrderPoolPrice(priceParam, true);

        if (oprv == null) {
            try {
                String orderInfoJson = JSON.toJSONString(priceParam);
                SystemAlertParam systemAlertParam = new SystemAlertParam();
                StringBuffer sb = new StringBuffer();
                sb.append("OrderInfo信息:").append(orderInfoJson).append("/n");
                systemAlertParam.setMessage(sb.toString());
                dingTalkBiz.sendSystemAlert(systemAlertParam);
            } catch (ApiException e) {
                log.info("钉钉机器人报错："+ e.getMessage());
            } catch (Exception e) {
                log.info("钉钉机器人报错："+ e.getMessage());
            }
                throw new BusinessException(5001, "未取得定价信息");
        }

        OrderPoolEntity order = orderRepository.findByExternalOrderId(param.getExternalOrderId());
        //创建订单
        if (order == null) {
            //order = OrderPoolConvertor.INSTANCE.convert(param);
            order = new OrderPoolEntity();
            order.setIdOrder(StringUtil.createOrderID(0));
            order.setCreateBy(Constants.Def_CreateBy);
        }

        //todo 2023.04.06
//        order.setIdMember(member.getIdMember());
//        order.setIdServicePriceType(oprv.getIdServicePriceType());
//        order.setOrderType(Constants.OrderType.APPOINTMENT);
//        order.setCarpoolType(Constants.OrderCarpoolType.Chartered);//拼车包车用这个
//        order.setStatus(Constants.OrderStatus.ORDER_STATUS_CREATED);
//        order.setPaymentStatus(Constants.PaymentStatus.UN_PAY);
//        order.setDivideAccountsStatus(Constants.DivideAccountsStatus.UN);
//        order.setReferenceDistance(oprv.getOrderDistance());
//        order.setEstimatedTime(oprv.getSpendTime());
//        float money = oprv.getTotalPrice();
//        order.setEstimatedMoney(money);
//        order.setOrderPriority(0);
//        order.setExternalOrderId(param.getExternalOrderId());
//        order.setUpdateBy(Constants.Def_CreateBy);

        order.setIdMember(idMember);
        order.setIdFranchisee(param.getIdFranchisee());
        order.setIdBrandHolder(param.getIdBrandHolder());
        order.setIdServicePriceType(oprv.getIdServicePriceType());
        order.setIdServiceType(param.getIdServiceType());
        order.setIdVehicleType(param.getIdVehicleType());
        order.setIdTask(param.getIdTask());
        order.setRegionCode(param.getRegionCode());
        order.setOrderType(Constants.OrderType.APPOINTMENT);
        order.setCarpoolType(Constants.OrderCarpoolType.Chartered);//拼车包车用这个
        order.setIdStation(param.getIdRailwayStation());
        order.setIdAirport(param.getIdAirport());
        order.setUserName(param.getUserName());
        order.setUserMobile(param.getUserMobile());
        order.setPassengerName(param.getUserName());//传值下单用户名
        order.setPassengerMobile(param.getPassengerMobile());
        int passengerNum = ((param.getPassengerNumber() == 0)) ? 1 : param.getPassengerNumber();
        order.setPassengerNumber(passengerNum);
        order.setAppointmentTime(DateUtil.parseLocalDateTime(param.getAppointmentTime()));
        if (null != param.getAssignTime())
            order.setAssignTime(DateUtil.parseLocalDateTime(param.getAssignTime()));
        order.setDriverLongitude(param.getDriverLongitude());
        if (null != param.getDeptime())
            order.setDeptime(DateUtil.parseLocalDateTime(param.getDeptime()));
        order.setStartAddress(param.getStartAddress());
        order.setStartAddressLongitude(param.getStartAddressLongitude());
        order.setStartAddressLatitude(param.getStartAddressLatitude());
        order.setEndAddress(param.getEndAddress());
        order.setEndAddressLongitude(param.getEndAddressLongitude());
        order.setEndAddressLatitude(param.getEndAddressLatitude());
        if (null != param.getDesttime())
            order.setDesttime(DateUtil.parseLocalDateTime(param.getDesttime()));
        order.setDropOffArea(param.getDropOffArea());
        order.setDropOffAreaLongitude(param.getDropOffAreaLongitude());
        order.setDropOffAreaLatitude(param.getDropOffAreaLatitude());
        order.setOrderSource(param.getOrderSource());
        order.setStatus(Constants.OrderStatus.ORDER_STATUS_CREATED);
        int paymentStatus = (param.getPaymentStatus() == null) ? Constants.PaymentStatus.UN_PAY : param.getPaymentStatus();
        order.setPaymentStatus(paymentStatus);
        int paymentRequitment = (param.getPaymentRequitment() == null) ? Constants.PaymentRequitment.IN_ADVANCE : param.getPaymentRequitment();
        order.setPaymentRequitment(paymentRequitment);
        order.setDivideAccountsStatus(Constants.DivideAccountsStatus.UN);
        order.setReferenceDistance(oprv.getOrderDistance());
        order.setEstimatedTime(oprv.getSpendTime());
        order.setEstimatedMoney(oprv.getTotalPrice());
        order.setOrderMoney(oprv.getTotalPrice());
        order.setOrderMemo(param.getOrderMemo());
        order.setOrderPriority(0);
        order.setExternalOrderId(param.getExternalOrderId());
        order.setFlightNo(param.getFlightNo());

        FranchiseeCommisionEntity franchiseeCommisionEntity = null;
        float driverRate = 0.75f;
        if (StringUtil.isNotBlank(order.getIdFranchisee()))
            franchiseeCommisionEntity = fcRepository.findByChannelAndIdFranchiseeAndModuleType(Constants.Channel.ALITRIP,
                    order.getIdFranchisee(), Constants.OrderModuleType.SPECIAL);
        if (franchiseeCommisionEntity != null) {
            driverRate =  franchiseeCommisionEntity.getDriverRate()/100;
            float driverIncome = order.getEstimatedMoney() * driverRate;
            if (order.getOrderMoney() != null) {
                driverIncome = order.getOrderMoney() * driverRate;
            }
            order.setDriverIncome(driverIncome);
        }

        if (order.getOrderSource() == Constants.OrderSource.ALITRIP ||
                order.getOrderSource() == Constants.OrderSource.XIAODUO||
                order.getOrderSource() == Constants.OrderSource.HUWO) {
            order.setPaymentStatus(Constants.PaymentStatus.ON_PAY);
            if (param.getOrderMoney() != null && param.getOrderMoney() > 0)
                order.setOrderMoney(param.getOrderMoney());
            if (param.getPayMoney() != null && param.getPayMoney() > 0)
                order.setPayMoney(param.getPayMoney());
            if (param.getCouponDiscount() != null && param.getCouponDiscount() > 0)
                order.setCouponDiscount(param.getCouponDiscount());
            if (param.getShopCouponDiscount() != null)
                order.setShopCouponDiscount(param.getShopCouponDiscount());
            if (order.getOrderMoney() != null) {
                float driverIncome = order.getOrderMoney() * driverRate;
                order.setDriverIncome(driverIncome);
            } else {
                float driverIncome = order.getEstimatedMoney() * driverRate;
                order.setDriverIncome(driverIncome);
            }
        }

        if (order.getOrderSource() == Constants.OrderSource.ALITRIP) {
            float shopDiscount = order.getEstimatedMoney() - order.getOrderMoney();
            if (shopDiscount <= 0)
                shopDiscount = 0;
            order.setShopCouponDiscount(shopDiscount);
        }

        log.info("newOrder信息：" + JSON.toJSONString(order));
        try {
            order = orderRepository.saveAndFlush(order);
        } catch (Exception e) {
            order = orderRepository.save(order);
        }

        //追加订单状态
        SpCarOrderStatusHistoryEntity orderStatus = new SpCarOrderStatusHistoryEntity();
        orderStatus.setIdOrder(order.getIdOrder());
        orderStatus.setStatus(order.getStatus());
        orderStatus.setCreateBy(Constants.Def_CreateBy);
        orderStatus.setMemo("运力商系统录入订单");
        orderStatusHistoryRepository.save(orderStatus);

        return order;
    }

    @Override
    public OrderPoolEntity createPoolCommonOrder(OrderPoolParam param) {

        //1，乘客账户存在时，前端未传值的情况下，取得乘客信息放到对应参数当中
        String idMember = param.getIdMember();
        if (StringUtil.isBlank(param.getIdMember())) {
            MemberEntity member = memberService.createNewMember(param.getUserMobile());
            idMember = member.getIdMember();
        }

        //定价ID未知时，取得并保存
        OrderPoolPriceParam priceParam = new OrderPoolPriceParam();
        priceParam.setRegionCode(param.getRegionCode());
        StringBuilder origins = new StringBuilder(param.getStartAddressLatitude()).append(",").append(param.getStartAddressLongitude());
        StringBuilder destinations = new StringBuilder(param.getEndAddressLatitude()).append(",").append(param.getEndAddressLongitude());
        priceParam.setIdFranchisee(param.getIdFranchisee());
        priceParam.setOrigins(origins.toString());
        priceParam.setDestinations(destinations.toString());
        priceParam.setIdServiceType(param.getIdServiceType());
        priceParam.setIdVehicleType(param.getIdVehicleType());
        priceParam.setIdStation(param.getIdRailwayStation());
        priceParam.setIdRailwayStation(param.getIdRailwayStation());
        priceParam.setIdAirport(param.getIdAirport());
        priceParam.setOrderBizType(param.getOrderBizType());
        priceParam.setCoordinateType(param.getCoordinateType());
        priceParam.setChannel(param.getChannel());
        priceParam.setAppointTime(param.getAppointmentTime());
        priceParam.setCarpoolType(param.getCarpoolType());
        log.info("priceParam信息：" + JSON.toJSONString(priceParam));
        //定价取得
        OrderPriceVO oprv = this.orderPoolCommonPrice(priceParam, true);

        if (oprv == null) {
            try {
                String orderInfoJson = JSON.toJSONString(priceParam);
                SystemAlertParam systemAlertParam = new SystemAlertParam();
                StringBuffer sb = new StringBuffer();
                sb.append("OrderInfo信息:").append(orderInfoJson).append("/n");
                systemAlertParam.setMessage(sb.toString());
                dingTalkBiz.sendSystemAlert(systemAlertParam);
            } catch (ApiException e) {
                log.info("钉钉机器人报错："+ e.getMessage());
            } catch (Exception e) {
                log.info("钉钉机器人报错："+ e.getMessage());
            }
            throw new BusinessException(5001, "未取得定价信息");
        }

        OrderPoolEntity order = orderRepository.findByExternalOrderId(param.getExternalOrderId());
        //创建订单
        if (order == null) {
            //order = OrderPoolConvertor.INSTANCE.convert(param);
            order = new OrderPoolEntity();
            order.setIdOrder(StringUtil.createOrderID(0));
            order.setCreateBy(Constants.Def_CreateBy);
        }

        //todo 2023.04.06
//        order.setIdMember(member.getIdMember());
//        order.setIdServicePriceType(oprv.getIdServicePriceType());
//        order.setOrderType(Constants.OrderType.APPOINTMENT);
//        order.setCarpoolType(Constants.OrderCarpoolType.Chartered);//拼车包车用这个
//        order.setStatus(Constants.OrderStatus.ORDER_STATUS_CREATED);
//        order.setPaymentStatus(Constants.PaymentStatus.UN_PAY);
//        order.setDivideAccountsStatus(Constants.DivideAccountsStatus.UN);
//        order.setReferenceDistance(oprv.getOrderDistance());
//        order.setEstimatedTime(oprv.getSpendTime());
//        float money = oprv.getTotalPrice();
//        order.setEstimatedMoney(money);
//        order.setOrderPriority(0);
//        order.setExternalOrderId(param.getExternalOrderId());
//        order.setUpdateBy(Constants.Def_CreateBy);

        order.setIdMember(idMember);
        order.setIdFranchisee(param.getIdFranchisee());
        order.setIdBrandHolder(param.getIdBrandHolder());
        order.setIdServicePriceType(oprv.getIdServicePriceType());
        order.setIdServiceType(param.getIdServiceType());
        order.setIdVehicleType(param.getIdVehicleType());
        order.setIdTask(param.getIdTask());
        order.setRegionCode(param.getRegionCode());
        order.setOrderType(Constants.OrderType.APPOINTMENT);
        order.setCarpoolType(Constants.OrderCarpoolType.Chartered);//拼车包车用这个
        order.setIdStation(param.getIdRailwayStation());
        order.setIdAirport(param.getIdAirport());
        order.setUserName(param.getUserName());
        order.setUserMobile(param.getUserMobile());
        order.setPassengerName(param.getUserName());//传值下单用户名
        order.setPassengerMobile(param.getPassengerMobile());
        int passengerNum = ((param.getPassengerNumber() == 0)) ? 1 : param.getPassengerNumber();
        order.setPassengerNumber(passengerNum);
        order.setAppointmentTime(DateUtil.parseLocalDateTime(param.getAppointmentTime()));
        if (null != param.getAssignTime())
            order.setAssignTime(DateUtil.parseLocalDateTime(param.getAssignTime()));
        order.setDriverLongitude(param.getDriverLongitude());
        if (null != param.getDeptime())
            order.setDeptime(DateUtil.parseLocalDateTime(param.getDeptime()));
        order.setStartAddress(param.getStartAddress());
        order.setStartAddressLongitude(param.getStartAddressLongitude());
        order.setStartAddressLatitude(param.getStartAddressLatitude());
        order.setEndAddress(param.getEndAddress());
        order.setEndAddressLongitude(param.getEndAddressLongitude());
        order.setEndAddressLatitude(param.getEndAddressLatitude());
        if (null != param.getDesttime())
            order.setDesttime(DateUtil.parseLocalDateTime(param.getDesttime()));
        order.setDropOffArea(param.getDropOffArea());
        order.setDropOffAreaLongitude(param.getDropOffAreaLongitude());
        order.setDropOffAreaLatitude(param.getDropOffAreaLatitude());
        order.setOrderSource(param.getOrderSource());
        order.setStatus(Constants.OrderStatus.ORDER_STATUS_CREATED);
        int paymentStatus = (param.getPaymentStatus() == null) ? Constants.PaymentStatus.UN_PAY : param.getPaymentStatus();
        order.setPaymentStatus(paymentStatus);
        int paymentRequitment = (param.getPaymentRequitment() == null) ? Constants.PaymentRequitment.IN_ADVANCE : param.getPaymentRequitment();
        order.setPaymentRequitment(paymentRequitment);
        order.setDivideAccountsStatus(Constants.DivideAccountsStatus.UN);
        order.setReferenceDistance(oprv.getOrderDistance());
        order.setEstimatedTime(oprv.getSpendTime());
        order.setEstimatedMoney(oprv.getTotalPrice());
        order.setOrderMoney(oprv.getTotalPrice());
        order.setOrderMemo(param.getOrderMemo());
        order.setOrderPriority(0);
        order.setExternalOrderId(param.getExternalOrderId());
        order.setFlightNo(param.getFlightNo());

        FranchiseeCommisionEntity franchiseeCommisionEntity = null;
        float driverRate = 0.75f;
        if (StringUtil.isNotBlank(order.getIdFranchisee()))
            franchiseeCommisionEntity = fcRepository.findByChannelAndIdFranchiseeAndModuleType(Constants.Channel.ALITRIP,
                    order.getIdFranchisee(), Constants.OrderModuleType.SPECIAL);
        if (franchiseeCommisionEntity != null) {
            driverRate =  franchiseeCommisionEntity.getDriverRate()/100;
            float driverIncome = order.getEstimatedMoney() * driverRate;
            if (order.getOrderMoney() != null) {
                driverIncome = order.getOrderMoney() * driverRate;
            }
            order.setDriverIncome(driverIncome);
        }

        if (order.getOrderSource() == Constants.OrderSource.ALITRIP ||
                order.getOrderSource() == Constants.OrderSource.XIAODUO||
                order.getOrderSource() == Constants.OrderSource.HUWO) {
            order.setPaymentStatus(Constants.PaymentStatus.ON_PAY);
            if (param.getOrderMoney() != null && param.getOrderMoney() > 0)
                order.setOrderMoney(param.getOrderMoney());
            if (param.getPayMoney() != null && param.getPayMoney() > 0)
                order.setPayMoney(param.getPayMoney());
            if (param.getCouponDiscount() != null && param.getCouponDiscount() > 0)
                order.setCouponDiscount(param.getCouponDiscount());
            if (param.getShopCouponDiscount() != null)
                order.setShopCouponDiscount(param.getShopCouponDiscount());
            if (order.getOrderMoney() != null) {
                float driverIncome = order.getOrderMoney() * driverRate;
                order.setDriverIncome(driverIncome);
            } else {
                float driverIncome = order.getEstimatedMoney() * driverRate;
                order.setDriverIncome(driverIncome);
            }
        }

        if (order.getOrderSource() == Constants.OrderSource.ALITRIP) {
            float shopDiscount = order.getEstimatedMoney() - order.getOrderMoney();
            if (shopDiscount <= 0)
                shopDiscount = 0;
            order.setShopCouponDiscount(shopDiscount);
        }

        log.info("newOrder信息：" + JSON.toJSONString(order));
        try {
            order = orderRepository.saveAndFlush(order);
        } catch (Exception e) {
            order = orderRepository.save(order);
        }

        //追加订单状态
        SpCarOrderStatusHistoryEntity orderStatus = new SpCarOrderStatusHistoryEntity();
        orderStatus.setIdOrder(order.getIdOrder());
        orderStatus.setStatus(order.getStatus());
        orderStatus.setCreateBy(Constants.Def_CreateBy);
        orderStatus.setMemo("运力商系统录入订单");
        orderStatusHistoryRepository.save(orderStatus);

        return order;
    }

    /**
     * 更新订单
     *
     * @param param
     * @return
     */
    @Override
    public OrderPoolEntity updatePoolOrder(OrderPoolParam param) {

        //1，乘客账户存在时，前端未传值的情况下，取得乘客信息放到对应参数当中
        MemberEntity member = memberService.createNewMember(param.getUserMobile());

        //定价ID未知时，取得并保存
        OrderPoolPriceParam priceParam = new OrderPoolPriceParam();
        priceParam.setRegionCode(param.getRegionCode());
        StringBuilder origins = new StringBuilder(param.getStartAddressLatitude()).append(",").append(param.getStartAddressLongitude());
        StringBuilder destinations = new StringBuilder(param.getEndAddressLatitude()).append(",").append(param.getEndAddressLongitude());
        priceParam.setIdFranchisee(param.getIdFranchisee());
        priceParam.setOrigins(origins.toString());
        priceParam.setDestinations(destinations.toString());
        priceParam.setIdServiceType(param.getIdServiceType());
        priceParam.setIdVehicleType(param.getIdVehicleType());
        priceParam.setIdRailwayStation(param.getIdRailwayStation());
        priceParam.setIdAirport(param.getIdAirport());
        priceParam.setOrderBizType(param.getOrderBizType());
        //定价取得
        OrderPriceVO oprv = this.getOrderPrice(priceParam);

        //创建订单
        OrderPoolEntity order = OrderPoolConvertor.INSTANCE.convert(param);
        //todo 2023.04.06
        order.setIdOrder(param.getIdOrder());
        order.setIdMember(member.getIdMember());
        order.setIdServicePriceType(oprv.getIdServicePriceType());
        order.setOrderType(Constants.OrderType.APPOINTMENT);
        order.setCarpoolType(Constants.OrderCarpoolType.Chartered);//拼车包车用这个
        int status = Constants.OrderStatus.ORDER_STATUS_CREATED;
        if (param.getStatus() != null)
            status = param.getStatus();
        order.setStatus(status);
        int paymentStatus = (param.getPaymentStatus() == null) ? Constants.PaymentStatus.UN_PAY : param.getPaymentStatus();
        order.setPaymentStatus(paymentStatus);
        int paymentRequitment = (param.getPaymentRequitment() == null) ? Constants.PaymentRequitment.IN_ADVANCE : param.getPaymentRequitment();
        order.setPaymentRequitment(paymentRequitment);
        order.setDivideAccountsStatus(Constants.DivideAccountsStatus.UN);
        order.setReferenceDistance(oprv.getOrderDistance());
        order.setEstimatedTime(oprv.getSpendTime());
        float money = oprv.getTotalPrice();
        order.setEstimatedMoney(money);
        order.setOrderPriority(0);
        order.setExternalOrderId(param.getExternalOrderId());
        if (param.getDriverIncome() != null)
            order.setDriverIncome(param.getDriverIncome());
//        order.setCreateBy(Constants.Def_CreateBy);
        order.setUpdateBy(Constants.Def_CreateBy);
        order = orderRepository.save(order);

        //追加订单状态
//        ExpressOrderStatusHistoryEntity orderStatus = new ExpressOrderStatusHistoryEntity();
//        orderStatus.setIdOrder(order.getIdOrder());
//        orderStatus.setStatus(order.getStatus());
//        orderStatus.setCreateBy("capacity");
//        orderStatus.setMemo("运力商系统录入订单");
//        orderStatusHistoryRepository.save(orderStatus);
        //success(MapUtil.builder("idRide","行程状态更新成功").build());
        return order;
    }

    @Override
    public void userCancelPoolOrder(String idOrder, String reason) {

        OrderPoolEntity order = orderRepository.findByIdOrder(idOrder);
        if (order == null)
            throw new BusinessException(5002, "订单不存在，请检查参数idOrder是否正确");
        if (order.getStatus() > Constants.OrderStatus.ORDER_STATUS_ARRIVED
                && order.getStatus() < Constants.OrderStatus.ORDER_STATUS_CANCEL)
            throw new BusinessException(5002, "订单已开始服务，无法删除,要删除请联系工作人员。");

        if (order.getOrderSource() == Constants.OrderSource.ALITRIP) {

            order.setStatus(Constants.OrderStatus.ORDER_STATUS_CANCEL);
            try {
                orderRepository.saveAndFlush(order);
            } catch (Exception e) {
                orderRepository.save(order);
            }

            //订单取消历史
            SpCarOrderCancelHistoryEntity cancelHistory = new SpCarOrderCancelHistoryEntity();
            cancelHistory.setIdOrder(order.getIdOrder());
            cancelHistory.setOperationType(Constants.OrderOperatorType.MEMBER);
            cancelHistory.setIdOperation(order.getPassengerMobile());
            cancelHistory.setReason(reason);
            cancelHistory.setReasonCode(Constants.OrderCancelType.OTHER_REASON);
            cancelHistory.setMemo(MessageTemplate.OrderStatus.USER_CANCEL);
            spOrderCancelHistoryRepository.save(cancelHistory);

            try {
                if (StringUtil.isNotBlank(order.getIdOrder())) {
                    DriverInfoVO driverInfoVO = driverService.driverInfo(order.getIdDriver());
                    smsBiz.sendCancelOrderSms(driverInfoVO.getDriverMobile(), order.getAppointmentTime(), order.getIdMember());
                }
            } catch (Exception e) {
            }

        } else {

            //移除订单到订单历史表
            SpCarOrderHistoryEntity entity = SpecialConvertor.INSTANCE.convert(order);
            entity.setStatus(Constants.OrderStatus.ORDER_STATUS_CANCEL);
            SpCarOrderHistoryRepository.save(entity);

            //添加订单删除历史记录
            SpCarOrderCancelHistoryEntity cancelHistoryEntity = new SpCarOrderCancelHistoryEntity();
            cancelHistoryEntity.setIdOrder(idOrder);
            cancelHistoryEntity.setOperationType(Constants.OrderOperatorType.MEMBER);
            cancelHistoryEntity.setIdOperation(order.getPassengerMobile());
            cancelHistoryEntity.setReasonCode(Constants.OrderCancelType.OTHER_REASON);
            cancelHistoryEntity.setMemo(MessageTemplate.OrderStatus.USER_CANCEL);
            orderCancelHistoryRepository.save(cancelHistoryEntity);

            //追加订单状态
            SpCarOrderStatusHistoryEntity orderStatus = new SpCarOrderStatusHistoryEntity();
            orderStatus.setIdOrder(entity.getIdOrder());
            orderStatus.setStatus(entity.getStatus());
            orderStatus.setCreateBy(Constants.Def_CreateBy);
            orderStatus.setMemo("用户取消订单");
            orderStatusHistoryRepository.save(orderStatus);

            orderRepository.delete(order);
        }

        try {
            OrderVO orderVO = OrderConvertor.INSTANCE.orderPoolToView(order);
            jPushService.sendOrderCancelMessage(orderVO);
        } catch (Exception e) {
        }

    }

    @Override
    public void cancelPoolOrder(String idOrder) {
        //OrderPoolEntity order = orderRepository.getById(idOrder);
        OrderPoolEntity order = orderRepository.findByIdOrder(idOrder);
        if (order == null)
            throw new BusinessException(5002, "订单不存在，请检查参数idOrder是否正确");
        if (order.getStatus() > Constants.OrderStatus.ORDER_STATUS_ARRIVED)
            throw new BusinessException(5002, "订单已开始服务，无法删除,要删除请联系工作人员。");

        if (order.getOrderSource() == Constants.OrderSource.ALITRIP) {

            throw new BusinessException(5002, "飞猪订单不能擅自取消！");

//            order.setVirtualOrderAccepted(1);
//            orderRepository.saveAndFlush(order);
//
//            //订单取消历史
//            SpCarOrderCancelHistoryEntity cancelHistory = new SpCarOrderCancelHistoryEntity();
//            cancelHistory.setIdOrder(order.getIdOrder());
//            cancelHistory.setOperationType(Constants.OrderOperatorType.DRIVER);
//            cancelHistory.setIdOperation(order.getIdDriver());
//            cancelHistory.setReason("虚拟转单操作");
//            cancelHistory.setReasonCode(Constants.OrderCancelType.OTHER_REASON);
//            cancelHistory
//                    .setMemo(String.format(MessageTemplate.ExOrderOperation.CANCEL_ORDER, "capacity", order.getIdOrder()));
//            spOrderCancelHistoryRepository.save(cancelHistory);

        } else {

            //移除订单到订单历史表
            SpCarOrderHistoryEntity entity = SpecialConvertor.INSTANCE.convert(order);
            entity.setStatus(Constants.OrderStatus.ORDER_STATUS_ADMIN_CANCELED);
            SpCarOrderHistoryRepository.save(entity);

            //添加订单删除历史记录
            SpCarOrderCancelHistoryEntity cancelHistoryEntity = new SpCarOrderCancelHistoryEntity();
            cancelHistoryEntity.setIdOrder(idOrder);
            cancelHistoryEntity.setOperationType(Constants.OrderOperatorType.SYSTEM);
            cancelHistoryEntity.setIdOperation(Constants.Def_CreateBy);
            cancelHistoryEntity.setReasonCode(Constants.OrderCancelType.OTHER_REASON);
            cancelHistoryEntity
                    .setMemo(String.format(MessageTemplate.ExOrderOperation.CANCEL_ORDER, "capacity", order.getIdOrder()));
            orderCancelHistoryRepository.save(cancelHistoryEntity);

            //追加订单状态
            SpCarOrderStatusHistoryEntity orderStatus = new SpCarOrderStatusHistoryEntity();
            orderStatus.setIdOrder(entity.getIdOrder());
            orderStatus.setStatus(entity.getStatus());
            orderStatus.setCreateBy(Constants.Def_CreateBy);
            orderStatus.setMemo("运力商工作人员取消订单");
            orderStatusHistoryRepository.save(orderStatus);

            orderRepository.delete(order);
        }

        try {
            OrderVO orderVO = OrderConvertor.INSTANCE.orderPoolToView(order);
            jPushService.sendOrderCancelMessage(orderVO);
        } catch (Exception e) {
        }

        //return success(MapUtil.builder("idOrder","订单已删除成功").build());
    }

    @Override
    public OrderVO virtualAcceptOrder(String idOrder, String idDriver) {
        OrderPoolEntity order = orderRepository.getById(idOrder);
        if (order.getStatus() > Constants.OrderStatus.ORDER_STATUS_ACCEPTED)
            throw new BusinessException(5002, "订单已开始服务，无法虚拟接单。");

        if (order.getStatus() == Constants.OrderStatus.ORDER_STATUS_ACCEPTED &&
                StringUtil.isNotBlank(order.getIdDriver())) {
            if (order.getVirtualOrderAccepted() == 1) {
                return OrderPoolConvertor.INSTANCE.convert2VO(order);
            } else {
                throw new BusinessException(5002, "订单已安排司机，如需更换司机请执行改派才做。");
            }
        }

        idDriver = AliTripTransferConstants.AliTrip_VirtualDriver.get(order.getIdFranchisee());

        DriverInfoVO driverInfoVO = driverService.driverInfo(idDriver);
        String driverName = StringUtil.isNotBlank(driverInfoVO.getNickName()) ? driverInfoVO.getNickName() : driverInfoVO.getRealName();
        //司机联系方式。格式：加号+国家区号+空格+当地电话号码 +86 13266365287
        String tel = driverInfoVO.getDriverMobile();

        if (null != order.getOrderSource()) {
            int orderSource = order.getOrderSource();
            //接受飞猪的订单
            if (Constants.OrderSource.ALITRIP == orderSource) {

                long confirmType = 0L;
                if (StringUtil.isNotBlank(order.getIdDriver()))
                    confirmType = 1L;

                /**
                 * 改派司机接口：
                 */
                AlitripCarOrderConfirmRequest.OrderConfirm orderConfirm = new AlitripCarOrderConfirmRequest.OrderConfirm();
                //JSON.toJSONString(orderConfirm);
                orderConfirm.setConfirmTime(DateUtil.getNowLocalDate());
                //0应答 1改派
                orderConfirm.setConfirmType(confirmType);
                orderConfirm.setOrderId(order.getExternalOrderId());
                orderConfirm.setProviderId(AliTripTransferConstants.ProviderIdWithMemberID.get(order.getIdMember()));
                String idHuwoOrder = order.getIdOrder();
                if (idHuwoOrder.contains("ZCHW"))
                    idHuwoOrder = idHuwoOrder.replace("ZCHW","");
                orderConfirm.setThirdOrderId(idHuwoOrder);
                //0:接送机 1：实时打车 2：租车(不传值默认为0)
                orderConfirm.setUseType(0L);
                //车辆描述,车辆颜色,候车地点等：红色,T3出口
//                String carDesc = String.format("%s,%s",param.getVehicleColor(),"黄花机场T1");
//                orderConfirm.setDriverCarDesc(carDesc);
                //司机车型名称:奔驰C200
                String carName = String.format("%s%s", driverInfoVO.getBrand(), driverInfoVO.getModel());
                orderConfirm.setDriverCarName(driverInfoVO.getBrand());
                orderConfirm.setDriverCarNo(driverInfoVO.getPlateNumber());
                orderConfirm.setDriverName(driverName);
                orderConfirm.setDriverCarColor(driverInfoVO.getColor());
                orderConfirm.setCarBrand(driverInfoVO.getBrand());
                orderConfirm.setCarModel(driverInfoVO.getModel());
                //TODO
                //String tel = "+8613142262045";

                String driverTel = tel;
                if (!driverTel.contains("+86"))
                    driverTel = String.format("+86 %s", tel);
                orderConfirm.setDriverTel(driverTel);
//                //车龄
//                orderConfirm.setCarAge();
//                //司机性别
//                orderConfirm.setDeriverGender();
                //司机图片，公网可访问链接
//                orderConfirm.setDriverPic();
//                orderConfirm.setCarPic();

//                log.info("orderConfirm:" + JSON.toJSONString(orderConfirm));
                String tenant = AliTripTransferConstants.MemberIDFindMerchant.get(order.getIdMember());
                AlitripCarOrderConfirmResponse res = alitripCarOpen.orderConfirm(orderConfirm, tenant);
//                log.info("data:" + res.getData());
//                log.info("message:" + res.getMessage());
//                log.info("messageCode:" + res.getMessageCode());

                if (res == null || res.getMessage() == null
                        || !(res.getMessage().equals("成功") || res.getMessage().toLowerCase(Locale.ROOT).equals("ok")))
                    throw new BusinessException(5002, "飞猪接口回调失败，请重新执行");

//                //飞猪订单状态查询接口
//                AlitripCarOrderQueryRequest req = new AlitripCarOrderQueryRequest();
//                req.setOrderId(param.getExternalOrderId());
//                AlitripCarOrderQueryResponse orderQueryResponse = alitripCarOpen.orderQuery(req);
//                orderQueryResponse.getFirstResult().getStatus();

            }
        }

        String dpInfo = driverName + "/" + tel;;
        OrderVO vo = orderService.virtualAcceptOrder(order, idDriver, dpInfo);

        return vo;
    }

    @Override
    public OrderVO virtualAcceptOrder(DispatchParam param) {
        if (StringUtil.isBlank(param.getIdOrder()))
            throw new BusinessException(4001, "订单号idOrder不能为空");

        String idDriver;
        if (StringUtil.isNotBlank(param.getIdDriver())) {
            idDriver = param.getIdDriver();
        } else {
            DriverEntity entity = driverService.findDriverByIdFranchiseeWithRand(param.getIdFranchisee());
            if (entity == null)
                throw new BusinessException(5002, "未找到该加盟商有注册完整司机");
            else
                idDriver = entity.getIdDriver();
        }

        return this.virtualAcceptOrder(param.getIdOrder(), idDriver);
    }

    /**
     * 订单检索查询
     *
     * @param param
     * @return
     */
    @Override
    public PagingResultVO<OrderPoolVO> search(SpListParam param) {
        //
        String idFranchiseeArr = franchiseeBiz.findIdFranArrByDispacther(param.getIdDispatcher());
        if (StringUtil.isNotBlank(idFranchiseeArr)) {
            param.setIdFranchiseeArr(idFranchiseeArr);
            param.setIdFranchisee(null);
        } else {
            idFranchiseeArr = franchiseeBiz.findIdFranArrByFinance(param.getIdDispatcher());
            if (StringUtil.isNotBlank(idFranchiseeArr)) {
                param.setIdFranchiseeArr(idFranchiseeArr);
                param.setIdFranchisee(null);
            }
        }

        List<OrderPoolVO> list = orderMapper.searchWithConditionsAndPaging(param);
        for (OrderPoolVO orderPoolVO :list) {
            orderPoolVO.setCity(HashMapConstants.idFranchiseeCityMap.get(orderPoolVO.getIdFranchisee()));
        }
        PagingResultVO<OrderPoolVO> rs = new PagingResultVO<>(orderMapper.searchWithConditionsAndPagingTotal(param), list);
        return rs;
    }

    /**
     * 订单检索查询
     *
     * @param param
     * @return
     */
    @Override
    public PagingResultVO<OrderPoolVO> getTodayOrderList(SpListParam param) {
//        param.setAppointmentTimeE(DateUtil.getStartTimeOfDay());
        param.setAppointmentTimeF(DateUtil.getYestodayLocalDate());;
        if (param.getHourRange()==null){
            param.setHourRange(Constants.OrderFastSearchType.ALl);
        }

        switch (param.getHourRange()) {
            case Constants.OrderFastSearchType.ALl:
                break;
//            case Constants.OrderModuleType.EXPRESS:
//                break;
            default:
                LocalDateTime appointmentTimeE = DateUtil.getXHoursLaterDateTime(param.getHourRange());
                param.setAppointmentTimeE(cn.hutool.core.date.DateUtil.format(appointmentTimeE,Constants.DATE_FORMAT));
                param.setAppointmentTimeF(DateUtil.getNowLocalDate());;
                break;
        }

        String idFranchiseeArr = franchiseeBiz.findIdFranArrByDispacther(param.getIdDispatcher());
        if (StringUtil.isNotBlank(idFranchiseeArr)) {
            param.setIdFranchiseeArr(idFranchiseeArr);
            param.setIdFranchisee(null);
        }
        PagingResultVO<OrderPoolVO> rs = new PagingResultVO<>(orderMapper.searchWithConditionsAndPagingTotal(param), orderMapper.searchWithConditionsAndPaging(param));
        return rs;
    }

    /**
     * 获取今日创建的快车订单
     *
     * @param param
     * @return
     */
    @Override
    public PagingResultVO<OrderPoolVO> getNewOrderListByRegionCode(SpListParam param) {
        SpListParam convert = Convert.convert(SpListParam.class, param);
        convert.setCreatTimeF(DateUtil.getStartTimeOfDay());
        convert.setCreatTimeE(DateUtil.getEndTimeOfDay());
        convert.setRegionCodes(param.getRegionCodes());
        return OrderPoolConvertor.INSTANCE.convertNew(orderService.searchWithConditionsAndPaging(convert));
    }

    /**
     * 司机派单(订单池)
     *
     * @param param
     * @return
     */
    @Transactional
    @Override
    public Boolean dispatchDriver(DispatchDriverParam param) {
        boolean result = false;
        OrderPoolEntity order = orderRepository.findByIdOrder(param.getIdOrder());

        if (order == null)
            throw new BusinessException(5002, "订单不存在，请检查参数idOrder是否正确");

        order = this.refresh(order);
        if (order.getStatus() >= Constants.OrderStatus.ORDER_STATUS_CANCEL)
            throw new BusinessException(5002, "订单已取消，无法派单");

        DriverInfoVO driverInfoVO = driverService.driverInfo(param.getIdDriver());
        Integer carpoolType = order.getCarpoolType();
        if (Constants.OrderCarpoolType.Chartered == carpoolType) {
            //用车类型不匹配
            if (!vehicleService.verifyVehicleType(driverInfoVO.getIdVehicleType(), order.getIdVehicleType()))
                throw new BusinessException(5002, "车辆类型不匹配，无法派单！");
        }

        int orderType = Constants.OrderType.APPOINTMENT;
        Duration dur = Duration.between(LocalDateTime.now(), order.getAppointmentTime());
        long minute = dur.toMinutes();
        //一小时以前
        if (minute <= 40) {
            orderType = Constants.OrderType.REALTIME;
        }

        // 实时单
        if (Constants.OrderType.REALTIME == orderType) {
            //派订单给任务
            OrderParam orderParam = new OrderParam();
            orderParam.setIdDriver(param.getIdDriver());
            orderParam.setModuleType(StringUtil.orderType(param.getIdOrder()));
            JobPlatformEntity task = jobPlatformBiz.assignOrderToJob(order, orderParam);

            // 1.更新订单状态任务ID
            orderRepository.updateIdTask(param.getIdOrder(), task.getIdTask(), param.getDispatcher());
        }

        if (driverInfoVO == null)
            throw new BusinessException(5002, "司机不存在，请检查参数idDriver是否正确");

        // 司机账户冻结不能派单
        if (driverInfoVO.getStatus() == Constants.DriverStatus.FREEZE)
            throw new BusinessException(5002, "司机账户被冻结,不能派单");

        // 实时单
        if (Constants.OrderType.REALTIME == order.getOrderType() && driverInfoVO.getStatus() != Constants.DriverStatus.ONLINE)
            throw new BusinessException(5002, "实时单只能指派空闲司机");

        //DriverProfileEntity driverProfile = driverProfileRepository.findByIdDriverProfile(driver.getIdDriverProfile());
        String driverInfo = driverInfoVO.getRealName() + "/" + driverInfoVO.getDriverMobile();

        if (null != order.getOrderSource()) {
            int orderSource = order.getOrderSource();
            //接受同程的订单
            if (Constants.OrderSource.TONGCHENG_RIDE == orderSource) {
                //ElongOrderParam elongParam = ThirdPartyOrderConvertor.INSTANCE.Convert2ElongParam(param);
                OrderStatusDTO dto = new OrderStatusDTO()
                        .setStatus(TongChengConstants.ELong_OrderType.get(Constants.OrderStatus.ORDER_STATUS_ACCEPTED))
                        .setDriverName(driverInfoVO.getNickName())
                        .setDriverPhone(driverInfoVO.getDriverMobile())
                        .setVehiclePlateNum(driverInfoVO.getPlateNumber())
                        .setVehicleColor(driverInfoVO.getColor())
                        .setVehicleModel(driverInfoVO.getModel())
                        .setVehicleBrand(driverInfoVO.getBrand());

                dto.setOrderId(order.getExternalOrderId());
                dto.setSupplierOrderId(order.getIdOrder());

                String idChannel = authService.findIdChannel(null, order.getIdFranchisee());
                if (StringUtil.isBlank(idChannel))
                    throw new BusinessException(5002, "未找到对应的同程渠道，请检查渠道ID");

                ResultVO resultVO = callback.orderStatus(idChannel, dto);
                if (resultVO.getStatus() != 200)
                    throw new BusinessException(5002, "同程接口回调失败，请重新执行");

            } else if (Constants.OrderSource.ALITRIP == orderSource) {
//                AlitripCarOrderAcceptRequest.OrderAccept orderAccept = new AlitripCarOrderAcceptRequest.OrderAccept();
//                orderAccept.setConfirmType(0L);
//                orderAccept.setOrderId(param.getExternalOrderId());
//                orderAccept.setProviderId(AliTripTransferConstants.ProviderId.get(AliTripTransferConstants.AppKey.LAOBING));
//                orderAccept.setThirdOrderId(param.getIdOrder());
//                //0:接送机 1：实时打车 2：租车(不传值默认为0)
//                orderAccept.setUseType(0L);
//                //接单司机纬度,接单司机经度
//                LiveLocation location = lastLocation.getLiveLocation(param.getIdDriver());
//                if (location != null) {
//                    orderAccept.setLatitude(String.valueOf(location.getLat()));
//                    orderAccept.setLongitude(String.valueOf(location.getLon()));
//                }
//                orderAccept.setAcceptTime(System.currentTimeMillis());
//
//                AlitripCarOrderAcceptResponse res = alitripCarOpen.orderAccept(orderAccept);
//                if (res.getResult().getCode() != 0)
//                    throw new BusinessException(5002, "飞猪接口回调失败，请重新执行");

                long confirmType = 0L;
                if (StringUtil.isNotBlank(order.getIdDriver()))
                    confirmType = 1L;

                /**
                 * 改派司机接口：
                 */
                AlitripCarOrderConfirmRequest.OrderConfirm orderConfirm = new AlitripCarOrderConfirmRequest.OrderConfirm();
                //JSON.toJSONString(orderConfirm);
                orderConfirm.setConfirmTime(DateUtil.getNowLocalDate());
                //0应答 1改派
                orderConfirm.setConfirmType(confirmType);
                orderConfirm.setOrderId(order.getExternalOrderId());
                orderConfirm.setProviderId(AliTripTransferConstants.ProviderIdWithMemberID.get(order.getIdMember()));
                String idOrder = param.getIdOrder();
                if (idOrder.contains("ZCHW"))
                    idOrder = idOrder.replace("ZCHW","");
                orderConfirm.setThirdOrderId(idOrder);
                //0:接送机 1：实时打车 2：租车(不传值默认为0)
                orderConfirm.setUseType(0L);
                //车辆描述,车辆颜色,候车地点等：红色,T3出口
//                String carDesc = String.format("%s,%s",param.getVehicleColor(),"黄花机场T1");
//                orderConfirm.setDriverCarDesc(carDesc);
                //司机车型名称:奔驰C200
                String carName = String.format("%s%s", driverInfoVO.getBrand(), driverInfoVO.getModel());
                orderConfirm.setDriverCarName(driverInfoVO.getBrand());
                //司机车牌号:浙A111111
                orderConfirm.setDriverCarNo(driverInfoVO.getPlateNumber());
                orderConfirm.setDriverName(driverInfoVO.getRealName());
                orderConfirm.setDriverCarColor(driverInfoVO.getColor());
                orderConfirm.setCarBrand(driverInfoVO.getBrand());
                orderConfirm.setCarModel(driverInfoVO.getModel());
                //司机联系方式。格式：加号+国家区号+空格+当地电话号码 +86 13266365287
                String tel = driverInfoVO.getDriverMobile();
                if (!tel.contains("+86"))
                    tel = String.format("+86 %s", tel);
                orderConfirm.setDriverTel(tel);
//                //车龄
//                orderConfirm.setCarAge();
//                //司机性别
//                orderConfirm.setDeriverGender();
                //司机图片，公网可访问链接
//                orderConfirm.setDriverPic();
//                orderConfirm.setCarPic();

//                log.info("orderConfirm:" + JSON.toJSONString(orderConfirm));
                String tenant = AliTripTransferConstants.MemberIDFindMerchant.get(order.getIdMember());
                AlitripCarOrderConfirmResponse res = alitripCarOpen.orderConfirm(orderConfirm, tenant);
//                log.info("data:" + res.getData());
//                log.info("message:" + res.getMessage());
//                log.info("messageCode:" + res.getMessageCode());
                if (res == null || res.getMessage() == null
                        || !(res.getMessage().equals("成功") || res.getMessage().toLowerCase(Locale.ROOT).equals("ok")))
                    throw new BusinessException(5002, "飞猪接口回调失败，请重新执行");

//                //飞猪订单状态查询接口
//                AlitripCarOrderQueryRequest req = new AlitripCarOrderQueryRequest();
//                req.setOrderId(param.getExternalOrderId());
//                AlitripCarOrderQueryResponse orderQueryResponse = alitripCarOpen.orderQuery(req);
//                orderQueryResponse.getFirstResult().getStatus();

            }
        }

        //司机车辆信息取得
        VehicleEntity dv = vehicleRepository.findByIdDriver(param.getIdDriver());

        // 2.更新订单司机信息
        result = orderRepository.updateDriver(param.getIdDriver(),
                driverInfoVO.getIdFleet(),
                driverInfo,
                Constants.OrderStatus.ORDER_STATUS_ACCEPTED,
                dv.getPlateNumber(),
                dv.getVehicleName(),
                LocalDateTime.now(),
                param.getIdOrder()) == 1;
        if (!result) {
            return false;
        }

        // 3.更新订单系统派单时间
//        orderRepository.updateAssignTime(param.getIdOrder(), LocalDateTime.now());

//        // 4.更新订单用车类型（0：实时 1：预约）
//        orderRepository.updateOrderType(param.getIdOrder(), orderType);

        // 实时单
        if (Constants.OrderType.REALTIME == orderType) {
            //更新司机状态
            result = driverRepository.driverUpdateStatus(Constants.DriverStatus.TAKE_ORDER, param.getIdDriver()) == 1;
            if (!result) {
                return false;
            }
            //更新司机上线任务状态
            result = driverRepository.driverUpdateOperationStatus(Constants.DriverOperationStatus.EXPRESS_ONLINE, param.getIdDriver()) == 1;
            if (result) {
                dispatchRepository.save(new SpCarOrderDispatchEntity(param));
            }
        }

        // TODO 订单操作记录
        SpCarOrderOperationHistory oph = new SpCarOrderOperationHistory();
        oph.setIdOrder(param.getIdOrder());
        oph.setIdFranchisee(order.getIdFranchisee());
        oph.setCreateBy(param.getDispatcher());
        oph.setOperation(String.format(MessageTemplate.ExOrderOperation.DISPATCH_ORDER,
                param.getDispatcher(),
                param.getIdOrder(),
                driverInfoVO.getRealName()));
        oph.setOperationFlag(0);
        orderOperationHistoryRepository.save(oph);

        //追加订单状态
        SpCarOrderStatusHistoryEntity orderStatus = new SpCarOrderStatusHistoryEntity();
        orderStatus.setIdOrder(param.getIdOrder());
        orderStatus.setStatus(Constants.OrderStatus.ORDER_STATUS_ACCEPTED);
        orderStatus.setCreateBy(Constants.Def_CreateBy);
        orderStatus.setMemo(oph.getOperation());
        orderStatusHistoryRepository.save(orderStatus);

        //给司机发短信
//        String vicheTypeName = vehicleBiz.findVehicleType(order.getIdVehicleType());
//        String flightNo = StringUtil.isNotBlank(order.getFlightNo()) ? order.getFlightNo() : "-";
//        String context = String.format(MessageTemplate.BizTravelSms.ORDER_DISPATCH_DRIVER, DateUtil.formatDateTime(order.getAppointmentTime()), flightNo, vicheTypeName, order.getPassengerMobile());
//        log.info("message:" + context);
//        smsBiz.sendSmsMessage(driverInfoVO.getDriverMobile(), context, order.getIdMember());

        smsBiz.sendDispacthOrderSms(driverInfoVO.getDriverMobile(), order.getAppointmentTime(), order.getIdVehicleType(), order.getFlightNo(), order.getPassengerMobile(), order.getIdMember());

        try {
            OrderVO orderVO = OrderConvertor.INSTANCE.orderPoolToView(order);
            jPushService.sendNewOrderMessage(orderVO);
        } catch (Exception e) {
            log.info("向司机手机推送订单消息失败");
        }

        return true;
    }

    /**
     * 快车司机改派
     *
     * @param param
     * @return
     */
    @Override
    public Boolean reDispatchDriver(DispatchDriverParam param) {

        // 检查订单状态
        OrderPoolEntity order = orderRepository.findByIdOrder(param.getIdOrder());
        if (order == null)
            throw new BusinessException(5002, "订单不存在，请检查参数idOrder是否正确");

        order = this.refresh(order);
        if (order.getOrderSource() == Constants.OrderSource.ALITRIP) {
            if (order.getStatus() > Constants.OrderStatus.ORDER_STATUS_IN_SERVICE) {
                throw new BusinessException(5002, "订单已开始服务，不能转派，如需改派请去服务订单列表强制改派");
            }
        } else {
            if (order.getStatus() > Constants.OrderStatus.ORDER_STATUS_GOTO_RESERVATION) {
                throw new BusinessException(5002, "订单已经在执行，不能转派，如需改派请联系管理员");
            }
        }

        if (StringUtil.isBlank(param.getIdDriver()))
            throw new BusinessException(5002, "未选定指派司机");

//        if (StringUtil.isNotBlank(order.getIdDriver()) && order.getIdDriver().equals(param.getIdDriver()))
//            throw new BusinessException(5002, "已经指定给当前司机");

        //DriverEntity driver = driverRepository.findByIdDriver(param.getIdDriver());

        DriverInfoVO driverInfoVO = driverService.driverInfo(param.getIdDriver());
        if (driverInfoVO == null)
            throw new BusinessException(5002, "司机不存在，请检查参数idDriver是否正确");

        // 司机账户冻结不能派单
        if (driverInfoVO.getStatus() == Constants.DriverStatus.FREEZE)
            throw new BusinessException(5002, "司机账户被冻结,不能派单");

        //用车类型不匹配
        if (!vehicleService.verifyVehicleType(driverInfoVO.getIdVehicleType(), order.getIdVehicleType()))
            throw new BusinessException(5002, "车辆类型不匹配，无法派单！");

        // 实时单
        if (Constants.OrderType.REALTIME == order.getOrderType() && driverInfoVO.getStatus() != Constants.DriverStatus.ONLINE)
            throw new BusinessException(5002, "实时单只能指派空闲司机");

        //DriverProfileEntity driverProfile = driverProfileRepository.findByIdDriverProfile(driver.getIdDriverProfile());
        String driverInfo = driverInfoVO.getRealName() + "/" + driverInfoVO.getDriverMobile();

        if (StringUtil.isBlank(order.getIdDriver()) || !order.getIdDriver().equals(param.getIdDriver())) {
            if (null != order.getOrderSource()) {
                int orderSource = order.getOrderSource();
                //接受同程的订单
                if (Constants.OrderSource.TONGCHENG_RIDE == orderSource) {
                    //ElongOrderParam elongParam = ThirdPartyOrderConvertor.INSTANCE.Convert2ElongParam(param);
                    OrderStatusDTO dto = new OrderStatusDTO()
                            .setStatus(TongChengConstants.ELong_OrderType.get(Constants.OrderStatus.ORDER_STATUS_ACCEPTED))
                            .setDriverName(driverInfoVO.getNickName())
                            .setDriverPhone(driverInfoVO.getDriverMobile())
                            .setVehiclePlateNum(driverInfoVO.getPlateNumber())
                            .setVehicleColor(driverInfoVO.getColor())
                            .setVehicleModel(driverInfoVO.getModel())
                            .setVehicleBrand(driverInfoVO.getBrand());

                    dto.setOrderId(order.getExternalOrderId());
                    dto.setSupplierOrderId(order.getIdOrder());

                    String idChannel = authService.findIdChannel(null, order.getIdFranchisee());
                    if (StringUtil.isBlank(idChannel))
                        throw new BusinessException(5002, "未找到对应的同程渠道，请检查渠道ID");

                    ResultVO resultVO = callback.orderStatus(idChannel, dto);
                    if (resultVO.getStatus() != 200)
                        throw new BusinessException(5002, "同程接口回调失败，请重新执行");

                } else if (Constants.OrderSource.ALITRIP == orderSource) {
//                AlitripCarOrderAcceptRequest.OrderAccept orderAccept = new AlitripCarOrderAcceptRequest.OrderAccept();
//                orderAccept.setConfirmType(0L);
//                orderAccept.setOrderId(param.getExternalOrderId());
//                orderAccept.setProviderId(AliTripTransferConstants.ProviderId.get(AliTripTransferConstants.AppKey.LAOBING));
//                orderAccept.setThirdOrderId(param.getIdOrder());
//                //0:接送机 1：实时打车 2：租车(不传值默认为0)
//                orderAccept.setUseType(0L);
//                //接单司机纬度,接单司机经度
//                LiveLocation location = lastLocation.getLiveLocation(param.getIdDriver());
//                if (location != null) {
//                    orderAccept.setLatitude(String.valueOf(location.getLat()));
//                    orderAccept.setLongitude(String.valueOf(location.getLon()));
//                }
//                orderAccept.setAcceptTime(System.currentTimeMillis());
//
//                AlitripCarOrderAcceptResponse res = alitripCarOpen.orderAccept(orderAccept);
//                if (res.getResult().getCode() != 0)
//                    throw new BusinessException(5002, "飞猪接口回调失败，请重新执行");

                    long confirmType = 0L;
                    if (StringUtil.isNotBlank(order.getIdDriver()))
                        confirmType = 1L;

                    /**
                     * 改派司机接口：
                     */
                    AlitripCarOrderConfirmRequest.OrderConfirm orderConfirm = new AlitripCarOrderConfirmRequest.OrderConfirm();
                    //JSON.toJSONString(orderConfirm);
                    orderConfirm.setConfirmTime(DateUtil.getNowLocalDate());
                    //0应答 1改派
                    orderConfirm.setConfirmType(confirmType);
                    orderConfirm.setOrderId(order.getExternalOrderId());
                    orderConfirm.setProviderId(AliTripTransferConstants.ProviderIdWithMemberID.get(order.getIdMember()));
                    String idOrder = param.getIdOrder();
                    if (idOrder.contains("ZCHW"))
                        idOrder = idOrder.replace("ZCHW","");
                    orderConfirm.setThirdOrderId(idOrder);
                    //0:接送机 1：实时打车 2：租车(不传值默认为0)
                    orderConfirm.setUseType(0L);
                    //车辆描述,车辆颜色,候车地点等：红色,T3出口
//                String carDesc = String.format("%s,%s",param.getVehicleColor(),"黄花机场T1");
//                orderConfirm.setDriverCarDesc(carDesc);
                    //司机车型名称:奔驰C200
                    String carName = String.format("%s%s", driverInfoVO.getBrand(), driverInfoVO.getModel());
                    orderConfirm.setDriverCarName(driverInfoVO.getBrand());
                    //司机车牌号:浙A111111
                    orderConfirm.setDriverCarNo(driverInfoVO.getPlateNumber());
                    orderConfirm.setDriverName(driverInfoVO.getRealName());
                    orderConfirm.setDriverCarColor(driverInfoVO.getColor());
                    orderConfirm.setCarBrand(driverInfoVO.getBrand());
                    orderConfirm.setCarModel(driverInfoVO.getModel());
                    //司机联系方式。格式：加号+国家区号+空格+当地电话号码 +86 13266365287
                    String tel = driverInfoVO.getDriverMobile();
                    if (!tel.contains("+86"))
                        tel = String.format("+86 %s", tel);
                    orderConfirm.setDriverTel(tel);
//                //车龄
//                orderConfirm.setCarAge();
//                //司机性别
//                orderConfirm.setDeriverGender();
                    //司机图片，公网可访问链接
//                orderConfirm.setDriverPic();
//                orderConfirm.setCarPic();

//                log.info("orderConfirm:" + JSON.toJSONString(orderConfirm));
                    String tenant = AliTripTransferConstants.MemberIDFindMerchant.get(order.getIdMember());
                    AlitripCarOrderConfirmResponse res = alitripCarOpen.orderConfirm(orderConfirm,tenant);
//                log.info("data:" + res.getData());
//                log.info("message:" + res.getMessage());
//                log.info("messageCode:" + res.getMessageCode());
                    if (res == null || res.getMessage() == null
                            || !(res.getMessage().equals("成功") || res.getMessage().toLowerCase(Locale.ROOT).equals("ok")))
                        throw new BusinessException(5002, "飞猪接口回调失败，请重新执行");

//                //飞猪订单状态查询接口
//                AlitripCarOrderQueryRequest req = new AlitripCarOrderQueryRequest();
//                req.setOrderId(param.getExternalOrderId());
//                AlitripCarOrderQueryResponse orderQueryResponse = alitripCarOpen.orderQuery(req);
//                orderQueryResponse.getFirstResult().getStatus();

                }
            }
        }
        //缓存保存

//        //司机车辆信息取得
//        VehicleEntity dv = vehicleRepository.findByIdDriver(param.getIdDriver());
        //更新订单司机
        boolean result = orderRepository.updateDriver(param.getIdDriver(),
                driverInfoVO.getIdFleet(),
                driverInfo,
                Constants.OrderStatus.ORDER_STATUS_ACCEPTED,
                driverInfoVO.getPlateNumber(),
                driverInfoVO.getVehicleName(),
                LocalDateTime.now(),
                param.getIdOrder()) == 1;
        if (result)
            dispatchRepository.save(new SpCarOrderDispatchEntity(param));

        // 3.更新订单系统派单时间
        //orderRepository.updateAssignTime(param.getIdOrder(), LocalDateTime.now());

        //给司机发短信
//        String vicheTypeName = vehicleBiz.findVehicleType(order.getIdVehicleType());
//        String flightNo = StringUtil.isNotBlank(order.getFlightNo()) ? order.getFlightNo() : "-";
//        String context = String.format(MessageTemplate.BizTravelSms.ORDER_DISPATCH_DRIVER, DateUtil.formatDateTime(order.getAppointmentTime()), flightNo, vicheTypeName, order.getPassengerMobile());
//        log.info("message:" + context);
//        smsBiz.sendSmsMessage(driverInfoVO.getDriverMobile(), context, order.getIdMember());

        smsBiz.sendDispacthOrderSms(driverInfoVO.getDriverMobile(), order.getAppointmentTime(), order.getIdVehicleType(), order.getFlightNo(), order.getPassengerMobile(), order.getIdMember());

        // TODO 订单操作记录
        SpCarOrderOperationHistory oph = new SpCarOrderOperationHistory();
        oph.setIdOrder(param.getIdOrder());
        oph.setIdFranchisee(order.getIdFranchisee());
        oph.setCreateBy(param.getDispatcher());
        oph.setOperation(String.format(MessageTemplate.ExOrderOperation.DISPATCH_ORDER,
                param.getDispatcher(),
                param.getIdOrder(),
                driverInfoVO.getRealName()));
        oph.setOperationFlag(0);
        orderOperationHistoryRepository.save(oph);

        try {
            OrderVO orderVO = OrderConvertor.INSTANCE.orderPoolToView(order);
            jPushService.sendNewOrderMessage(orderVO);
        } catch (Exception e) {
            log.info("向司机手机推送订单消息失败");
        }

        return result;
    }

    @Override
    public OrderPoolVO orderPoolInfo(String idOrder) {
        OrderPoolEntity entity = orderRepository.findByIdOrder(idOrder);
        if (entity == null)
            throw new BusinessException(5002, "订单号不存在请检查");
        return OrderPoolConvertor.INSTANCE.convert(entity);
    }

    /**
     * 订单详情
     *
     * @param idOrder
     * @return
     */
    @Override
    public SpDetailVO spOrderDetail(String idOrder) {

        try {
            this.refresh(idOrder);
        } catch (Exception e) {
        }

        List<SpDetailVO.StatusHistory> statusHistories = orderMapper.spOrderDetailHistory(idOrder);
        List<SpDetailVO.StatusHistory> statusHistoriesR = new ArrayList<>();
        SpDetailVO.Base base = orderMapper.spOrderDetailBase(idOrder);
        if (base == null)
            throw new BusinessException(5002, "订单号不存在请检查");

        ArrayList<String> child;
        OrderPoolEntity orderEntity = orderRepository.findById(idOrder).orElse(null);
        if (orderEntity==null){
             SpCarOrderHistoryEntity oh = SpCarOrderHistoryRepository.findById(idOrder).orElse(null);
             orderEntity = OrderPoolConvertor.INSTANCE.convertHistory(oh);
        }

        SpCarOrderCancelHistoryEntity och = orderCancelHistoryRepository.findById(idOrder).orElse(null);

        for (SpDetailVO.StatusHistory v : statusHistories) {
            child = new ArrayList<>();
            switch (v.getStatus()) {
                case 0://乘客发单
                    v.setTitle("乘客发单");
                    child.add(StrUtil.join(":", "发单时间", v.getCreateTime()));
                    child.add(StrUtil.join(":", "预估里程/时长", StrUtil.builder().append(orderEntity.getReferenceDistance()).append("公里/").append(orderEntity.getEstimatedTime()).append("分钟")));
                    child.add(StrUtil.join(":", "预估价格", "￥" + orderEntity.getEstimatedMoney()));
                    statusHistoriesR.add(v);
                    break;
//                case 1://平台派单
//                    v.setTitle("平台派单");
//                    child.add(StrUtil.join(":","车牌号",StrUtil.builder().append(orderEntity.getPlateNumber())));
//                    child.add(StrUtil.join(":","车辆",StrUtil.builder().append(orderEntity.getModel())));
//                    child.add(StrUtil.join(":","预估接驾",StrUtil.builder().append("待定")));
//                    statusHistoriesR.add(v);
//                    break;
                case 2://司机接单
                    if (orderEntity.getIdDriver() != null) {
                        v.setTitle("司机接单");
                        VehicleEntity dv = vehicleRepository.findByIdDriver(orderEntity.getIdDriver());
                        child.add(StrUtil.join(":", "接单时间", v.getCreateTime()));
                        child.add(StrUtil.join(":", "车牌号", StrUtil.builder().append(dv.getPlateNumber())));
                        //child.add(StrUtil.join(":","车辆",StrUtil.builder().append(orderEntity.getModel())));
                        child.add(StrUtil.join(":", "预估接驾里程/时长", StrUtil.builder().append("待定")));
                        statusHistoriesR.add(v);
                    }

                    break;
                case 4://司机到达上车点
                    v.setTitle("司机到达上车点");
                    child.add(StrUtil.join(":", "到达上车地点时间", v.getCreateTime()));
                    child.add(StrUtil.join(":", "真实接驾里程/时长", StrUtil.builder().append("待定")));
                    statusHistoriesR.add(v);
                    break;
                case 5://乘客上车
                    v.setTitle("乘客上车");
                    child.add(StrUtil.join(":", "上车时间", v.getCreateTime()));
                    statusHistoriesR.add(v);
                    break;
                case 6://到达目的地
                    v.setTitle("到达目的地");
                    child.add(StrUtil.join(":", "到达时间", v.getCreateTime()));
                    child.add(StrUtil.join(":", "实际里程", orderEntity.getOrderDistance()));
                    statusHistoriesR.add(v);
                    break;
                case 7://未支付
                    v.setTitle("订单待支付");
                    child.add(StrUtil.join(":", "支付状态", StrUtil.builder().append("未支付")));
                    child.add(StrUtil.join(":", "支付时间", v.getCreateTime()));
                    child.add(StrUtil.join(":", "乘客应付", orderEntity.getPayMoney()));
                    child.add(StrUtil.join(":", "商家实收", orderEntity.getOrderMoney()));
                    child.add(StrUtil.join(":", "司机应得", orderEntity.getDriverIncome()));
                    statusHistoriesR.add(v);
                    break;
                case 8://已支付
                    v.setTitle("订单支付");
                    child.add(StrUtil.join(":", "支付状态", StrUtil.builder().append("已支付")));
                    child.add(StrUtil.join(":", "支付时间", v.getCreateTime()));
                    child.add(StrUtil.join(":", "乘客应付", orderEntity.getPayMoney()));
                    child.add(StrUtil.join(":", "商家实收", orderEntity.getOrderMoney()));
                    child.add(StrUtil.join(":", "司机应得", orderEntity.getDriverIncome()));
                    statusHistoriesR.add(v);
                    break;
                case 11://乘客下单后取消订单 用户取消、取消原因、操作时间
                    v.setTitle("已取消");
                    child.add("用户取消");
                    if (och != null) {
                        child.add(StrUtil.join(":", "取消原因", och.getReason()));
                        child.add(StrUtil.join(":", "操作时间", och.getCreateTime()));
                    }
                    statusHistoriesR.add(v);
                    break;
//                case 12://司机已拒绝
//                    v.setTitle("司机已拒绝");
//                    child.add(StrUtil.join(":","真实接驾",StrUtil.builder().append("待定")));
//                    statusHistoriesR.add(v);
//                    break;
                case 13://系统已销单
                    v.setTitle("已取消");
                    child.add("系统取消");
                    if (och != null) {
                        child.add(StrUtil.join(":", "取消原因", och.getReason()));
                        child.add(StrUtil.join(":", "操作时间", och.getCreateTime()));
                    }
                    statusHistoriesR.add(v);
                    break;
                case 14://司机已取消
                    v.setTitle("已取消");
                    child.add("司机取消");
                    if (och != null) {
                        child.add(StrUtil.join(":", "取消原因", och.getReason()));
                        child.add(StrUtil.join(":", "操作时间", och.getCreateTime()));
                    }
                    statusHistoriesR.add(v);
                    break;
                case 15://客服已取消
                    v.setTitle("已取消");
                    child.add("客服取消");
                    if (och != null) {
                        child.add(StrUtil.join(":", "取消原因", och.getReason()));
                        child.add(StrUtil.join(":", "操作时间", och.getCreateTime()));
                    }
                    statusHistoriesR.add(v);
                    break;
            }
            v.setChild(child);
        }
        return new SpDetailVO(base, statusHistoriesR, null);
    }

    @Override
    public Boolean spOrderDestroy(SpOrderDestroyParam param) {
        OrderPoolEntity orderEntity;
        try {
            orderEntity = orderRepository.findById(param.getIdOrder()).get();
            if (orderEntity.getStatus() == Constants.OrderStatus.ORDER_STATUS_ADMIN_CANCELED)
                throw new BusinessException(5002, "该订单已被销单,无法重复销单");
        } catch (NoSuchElementException e) {
            throw new BusinessException(5002, "订单ID[idOrder]不存在,请检查");
        }
        orderEntity.setStatus(Constants.OrderStatus.ORDER_STATUS_ADMIN_CANCELED);
        orderRepository.save(orderEntity);
        return destroyRepository.save(ExpressConvertor.INSTANCE.convert(param)) != null;
    }

    @Override
    public Boolean spReMemo(String idOrder, String memo) {
        return orderMapper.spReMemo(idOrder, memo);
    }

    /**
     * 订单支付详情
     *
     * @param idOrder
     * @return
     */
    @Override
    public OrderBillInfoVO getOrderBillInfo(String idOrder) {

        OrderPoolEntity order = orderRepository.findById(idOrder).orElse(null);
        if (order==null){
            SpCarOrderHistoryEntity oh = SpCarOrderHistoryRepository.findById(idOrder).orElse(null);
            order = OrderPoolConvertor.INSTANCE.convertHistory(oh);
        }
        if (order == null)
            throw new BusinessException(5002, "订单号不存在请检查");

        SpCarOrderSettlementEntity es = orderSettlementRepository.findByIdOrder(idOrder);
        SpecialDriverAccountDetailEntity ed = accountDetailRepository.findByRelateOrderNo(idOrder);

        if (es == null)
            es = new SpCarOrderSettlementEntity();
        if (ed == null)
            ed = new SpecialDriverAccountDetailEntity();

        OrderBillInfoVO.PassengerBill pb = new OrderBillInfoVO.PassengerBill();
        /** 总价 */
        pb.setTotal(es.getOrderTotal());
        /** 基础费 */
        pb.setBasic(es.getOrderMoney());
        /** 时长费 */
        pb.setDuration(0F);
        /** 远途费 */
        pb.setLongDistance(es.getOrderLongDistanceMoney());
        /** 等待费 */
        pb.setWaiting(0F);
        /** 加价费 */
        pb.setPlus(0F);
        OrderBillInfoVO.PassengerPayInfo pp = new OrderBillInfoVO.PassengerPayInfo();
        /** 支付金额 */
        pp.setPayMoney(order.getPayMoney());
        /** 支付时间 */
        if (es.getPayTime() != null) {
            pp.setPayTime(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(es.getPayTime()));
        }
        /** 支付状态 */
        pp.setPayStatus(Constants.Payment_Status.get(order.getPaymentStatus()));
        /** 支付渠道 */
        pp.setPayChannel(Constants.Payment_Type.get(es.getPaymentType()));
        /** 发票状态 */
        pp.setInvoiceStatus("-");
        /** 退款费用 */
        pp.setRefund(0F);
        /** 高速费 */
        pp.setHighSpeed(0F);
        /** 停车费 */
        pp.setParking(0F);
        /** 路桥费 */
        pp.setBridge(es.getOrderRoadMoney());
        /** 限时折扣 */
        pp.setDiscount(0F);
        /** 其他费 */
        pp.setOther(es.getOrderOther());
        /** 节假日服务费 */
        pp.setHoliday(0F);

        OrderBillInfoVO.DriverBill db = new OrderBillInfoVO.DriverBill();
        /** 总价 */
        if (ed != null) {
            db.setTotal(ed.getMoney());
        } else {
            db.setTotal(0F);
        }
        /** 基础费 */
        db.setBasic(0F);
        /** 时长费 */
        db.setDuration(0F);
        /** 里程费 */
        db.setMileage(0F);
        /** 高速费 */
        db.setHighSpeed(0F);
        /** 停车费 */
        db.setParking(0F);
        /** 路桥费 */
        db.setBridge(0F);
        /** 远途费 */
        db.setLongDistance(0F);
        /** 其他费 */
        db.setOther(0F);
        /** 免佣补贴金额 */
        db.setAllowance(0F);
        /** 节假日服务费 */
        db.setHoliday(0F);
        /** 信息服务费 */
        db.setInformation(0F);

        return new OrderBillInfoVO(pb, pp, db);
    }

    @Override
    public PagingResultVO<SpSettlementViewVO> spCarOrderBillViewLst(SpCarSettlementViewListParam param) {
        Page<SpSettlementViewVO> page = orderSettlementRepository.findByIdFranchisee(param.getIdFranchisee(), PageRequest.of(param.getPageIndex() - 1, param.getPageSize()));
        return new PagingResultVO<>(page.getTotalElements(), page.getContent());
    }

    @Override
    public PagingResultVO<OrderPoolVO> dispatherOrderPoolSearch(DispatcherSearchOrderParam param, Boolean forHistory) {
        //取得调度员管理的运力商城市
        //List<String> idFranchiseeArr =;
        SpListParam spListParam = OrderConvertor.INSTANCE.convert2SpParam(param);
        return new PagingResultVO(orderMapper.searchWithConditionsAndPagingTotal(spListParam), orderMapper.searchWithConditionsAndPaging(spListParam));
    }

    /**
     * 站点价格按线路按人头收费计算方法
     *
     * @param param
     * @return
     */
    private OrderPriceVO calRailwayOrderPrice(OrderPoolPriceParam param) {

        float money = 0;
        float base_price = 0;
        float other_price = 0;

        RailwayStationPriceEntity price = railwayPriceRepository.findByIdStation(param.getIdFranchisee(),
                param.getIdRailwayStation(), param.getIdServiceType(), param.getIdVehicleType());

        if (price != null) {
            money = price.getServicePrice();
            float od = param.getOrderDistance();
            if (od > price.getMaxServiceMileage()) {
                float ltp = od - price.getMaxServiceMileage();
                money = money + ltp * price.getExceedingMileagePrice();
            }

        } else {
            return null;
            //throw new BusinessException(5002,"未找到对应的定价方案");
        }

        base_price = money - other_price;
        OrderPriceVO opv = new OrderPriceVO();
        opv.setIdServicePriceType(price.getIdServicePriceType());
        opv.setTotalPrice(Convert.toFloat(new BigDecimal(money).setScale(2, RoundingMode.HALF_UP).toString()));
        opv.setBasePrice(Convert.toFloat(new BigDecimal(base_price).setScale(2, RoundingMode.HALF_UP).toString()));
        opv.setOtherPrice(Convert.toFloat(new BigDecimal(other_price).setScale(2, RoundingMode.HALF_UP).toString()));
        opv.setOrderDistance(param.getOrderDistance());
        opv.setSpendTime(param.getSpendTime());

        return opv;
    }

    /**
     * 站点价格按线路按人头收费计算方法
     *
     * @param param
     * @return
     */
    private OrderPriceVO calAirportOrderPrice(OrderPoolPriceParam param) {

        float money = 0;
        float base_price = 0;
        float other_price = 0;

        AirportPriceEntity price = airportPriceRepository.findByIdAirport(param.getIdFranchisee(), param.getIdAirport(), param.getIdServiceType(), param.getIdVehicleType());

        if (price != null) {
            money = price.getServicePrice();
            float od = param.getOrderDistance();
            if (od > price.getMaxServiceMileage()) {
                float ltp = od - price.getMaxServiceMileage();
                money = money + ltp * price.getExceedingMileagePrice();
            }

        } else {
            return null;
            //throw new BusinessException(5002,"未找到对应的定价方案");
        }

        base_price = money - other_price;
        OrderPriceVO opv = new OrderPriceVO();
        opv.setIdServicePriceType(price.getIdServicePriceType());
        opv.setTotalPrice(Convert.toFloat(new BigDecimal(money).setScale(2, RoundingMode.HALF_UP).toString()));
        opv.setBasePrice(Convert.toFloat(new BigDecimal(base_price).setScale(2, RoundingMode.HALF_UP).toString()));
        opv.setOtherPrice(Convert.toFloat(new BigDecimal(other_price).setScale(2, RoundingMode.HALF_UP).toString()));
        opv.setOrderDistance(param.getOrderDistance());
        opv.setSpendTime(param.getSpendTime());

        return opv;
    }

    /**
     * 解析接送机和接送站定价用的方法
     *
     * @param param
     * @param priceTxt
     * @return
     */
    private OrderPriceVO findPriceContent(OrderPoolPriceParam param, String priceTxt, String idPrice) {
        OrderPriceVO priceVO = new OrderPriceVO();

        float money = 0;
        float basePrice = 0;
        float otherPrice = 0;

        PriceContent priceContent = null;
        LocalDateTime l = DateUtil.parseLocalDateTime(param.getAppointTime());
        int appointTime = l.getHour() * 100 + l.getMinute();
        if (StringUtil.isNotBlank(priceTxt)) {
            JSONObject priceRule = JSONObject.parseObject(priceTxt);
            JSONArray array;
            if (Constants.OrderCarpoolType.Chartered == param.getCarpoolType()) {
                array = priceRule.getJSONArray("chartered");
            } else {
                array = priceRule.getJSONArray("carpool");
            }

            List<PriceContent> lst = JSON.parseArray(array.toString(), PriceContent.class);
            if (lst != null && lst.size() > 0) {
                for (PriceContent content : lst) {
                    //预约时间相匹配
                    String appointmentTime = content.getAppointment_time();
                    if (StringUtil.isBlank(appointmentTime)) {
                        priceContent = content;
                    } else {
                        String[] timeArr = appointmentTime.replace(":","").replace(".","").split("-");
                        int startTime = Integer.valueOf(timeArr[0]);
                        int endTime = Integer.valueOf(timeArr[1]);
                        if (endTime >= startTime) {
                            if (appointTime >= startTime && appointTime <= endTime) {
                                priceContent = content;
                                break;
                            }
                        } else {
                            if ((appointTime >= startTime && appointTime <= 2400) || (appointTime <= endTime)) {
                                priceContent = content;
                                break;
                            }
                        }
                    }
                }
            } else {
                throw new BusinessException(5002, "定价内容不存在,请检查");
            }

            if (priceContent != null) {
                //log.debug("PriceContent：{}", JSON.toJSONString(priceContent));
                basePrice = priceContent.getService_price()/100;
                int od = (int) (param.getOrderDistance() * 1000);
                int ox;
                int prevServiceMileage = priceContent.getService_mileage();
                boolean calDone = false;

                if (od > priceContent.getService_mileage()) {
                    String kilometerPriceRule = priceContent.getKilometer_price_rule();
                    if (StringUtil.isNotBlank(kilometerPriceRule)) {
                        List<KilometerPriceRule> ruleList = JSON.parseArray(kilometerPriceRule, KilometerPriceRule.class);
                        int i = 1;
                        while (i - 1 < ruleList.size()) {
                            for (int j = 0; j < ruleList.size(); j ++) {
                                KilometerPriceRule rule = ruleList.get(j);
                                if (rule.getSection() == i) {
                                    int mileage = rule.getService_mileage();
                                    ox = (od - mileage) > 0 ? (mileage - prevServiceMileage) : (od - prevServiceMileage);
                                    otherPrice = otherPrice + rule.getPre_price() * ox/100000;
                                    prevServiceMileage = mileage;
                                    //log.info("section:"+ i +" ox:"+ox + " otherPrice:"+otherPrice);
                                    if (od - mileage <= 0) {
                                        calDone = true;
                                    }
                                    i = i + 1;
                                    break;
                                }
                            }

                            if (calDone)
                                break;
                        }
                    }
                }
            } else {
                return null;
            }
        } else {
            return null;
        }

        HashMap<String,Float> result = new HashMap<>();
        Float rate = 1f;
        Float addMoney = 0f;

        try {

            //log.info("溢价解析开始");
            List<SpPremiumPriceEntity> lst = spPremiumPriceRepository.findByIdPrice(idPrice, 1);
            if (lst != null && lst.size() > 0) {
                for (SpPremiumPriceEntity spPremiumPriceEntity : lst) {
                    result = calSpPremiumPrice(spPremiumPriceEntity, l);
                    if (result != null) {
                        break;
                    }
                }
            } else {
                lst = spPremiumPriceRepository.findByIdFranchisee(param.getIdFranchisee(), 1);
                if (lst != null && lst.size() > 0) {
                    for (SpPremiumPriceEntity spPremiumPriceEntity : lst) {
                        result = calSpPremiumPrice(spPremiumPriceEntity, l);
                        if (result != null) {
                            break;
                        }
                    }
                }
            }

            if (result != null) {
                log.info("溢价结果："+ result.toString());
                if (result.get("addMoney") != null)
                    addMoney = result.get("addMoney").floatValue();
                if (result.get("rate") != null)
                    rate = result.get("rate").floatValue();
            }

            //log.info("溢价解析结束");
        } catch (Exception e) {
            log.info("溢价解析错误："+ e.getMessage());
        }

        float originPrice = basePrice;
        basePrice = basePrice * rate + param.getMarkUpPrice()/100 + addMoney;
        otherPrice = otherPrice * rate;
        money = basePrice + otherPrice;
        priceVO.setTotalPrice(Convert.toFloat(new BigDecimal(money).setScale(2, RoundingMode.HALF_UP).toString()));
        priceVO.setBasePrice(Convert.toFloat(new BigDecimal(basePrice).setScale(2, RoundingMode.HALF_UP).toString()));
        priceVO.setOtherPrice(Convert.toFloat(new BigDecimal(otherPrice).setScale(2, RoundingMode.HALF_UP).toString()));
        priceVO.setAddPrice(basePrice - originPrice);

        return priceVO;
    }

    /**
     * 解析接送机和接送站定价用的方法
     *
     * @param param
     * @param priceTxt
     * @return
     */
    private OrderPriceVO findCommonPriceContent(OrderPoolPriceParam param, String priceTxt, String idPrice) {
        OrderPriceVO priceVO = new OrderPriceVO();

        float money = 0;
        float basePrice = 0;
        float otherPrice = 0;

        PriceContent2 priceContent = null;
        LocalDateTime l = DateUtil.parseLocalDateTime(param.getAppointTime());
        int appointTime = l.getHour() * 100 + l.getMinute();
        if (StringUtil.isNotBlank(priceTxt)) {
            JSONObject priceRule = JSONObject.parseObject(priceTxt);
            JSONArray array;
            if (Constants.OrderCarpoolType.Chartered == param.getCarpoolType()) {
                array = priceRule.getJSONArray("chartered");
            } else {
                array = priceRule.getJSONArray("carpool");
            }

            List<PriceContent2> lst = JSON.parseArray(array.toString(), PriceContent2.class);
            if (lst != null && lst.size() > 0) {
                for (PriceContent2 content : lst) {
                    //预约时间相匹配
                    String appointmentTime = content.getAppointment_time();
                    if (StringUtil.isBlank(appointmentTime)) {
                        priceContent = content;
                    } else {
                        String[] timeArr = appointmentTime.replace(":","").replace(".","").split("-");
                        int startTime = Integer.valueOf(timeArr[0]);
                        int endTime = Integer.valueOf(timeArr[1]);
                        if (endTime >= startTime) {
                            if (appointTime >= startTime && appointTime <= endTime) {
                                priceContent = content;
                                break;
                            }
                        } else {
                            if ((appointTime >= startTime && appointTime <= 2400) || (appointTime <= endTime)) {
                                priceContent = content;
                                break;
                            }
                        }
                    }
                }
            } else {
                throw new BusinessException(5002, "定价内容不存在,请检查");
            }

            if (priceContent != null) {
                //log.debug("PriceContent：{}", JSON.toJSONString(priceContent));
                basePrice = priceContent.getService_price()/100;
                int orderDistance = (int) (param.getOrderDistance() * 1000);
                int ox = 0;
                int prevServiceMileage = priceContent.getService_mileage();
                int prePrice = priceContent.getPre_price();
                int preServicePrice = priceContent.getService_price();
                boolean calDone = false;

                if (orderDistance > priceContent.getService_mileage()) {
                    String kilometerPriceRule = priceContent.getKilometer_common_price_rule();
                    if (StringUtil.isNotBlank(kilometerPriceRule)) {

                        List<KilometerCommonPriceRule> ruleList = JSON.parseArray(kilometerPriceRule, KilometerCommonPriceRule.class);
                        int i = 1;
                        int size = ruleList.size();
                        while (i - 1 < size) {
                            for (int j = 0; j < size; j ++) {
                                KilometerCommonPriceRule rule = ruleList.get(j);
                                if (rule.getSection() == i) {
                                    int mileage = rule.getService_mileage();
                                    if (i == size) {
                                        if (orderDistance >= mileage) {
                                            ox = orderDistance - mileage;
                                            basePrice = rule.getService_price()/100;
                                            otherPrice = (rule.getPre_price() * ox)/100000;
                                            log.info("rule max 段数:" + i + "basePrice："+ basePrice + "ox："+ ox + "pre_price："+ rule.getPre_price() + "otherPrice："+  otherPrice);
                                            calDone = true;
                                        } else {
                                            ox = (orderDistance > prevServiceMileage) ? orderDistance - prevServiceMileage : 0;
                                            basePrice = preServicePrice/100;
                                            otherPrice = (prePrice * ox)/100000;
                                        }
                                    } else {
                                        if (orderDistance < rule.getService_mileage()) {
                                            ox = (orderDistance > prevServiceMileage) ? orderDistance - prevServiceMileage : 0;
                                            basePrice = preServicePrice/100;
                                            otherPrice = (prePrice * ox)/100000;
                                            calDone = true;
                                            break;
                                        } else {
                                            preServicePrice = rule.getService_price();
                                            prePrice = rule.getPre_price();
                                            prevServiceMileage = rule.getService_mileage();
                                        }
                                    }
                                    log.info("KilometerPriceRule2 段数:" + i + "basePrice："+ basePrice + "ox："+ ox + "otherPrice："+  otherPrice);
                                    i = i + 1;
                                    break;
                                }
                            }

                            if (calDone)
                                break;
                        }
                    }
                }
            } else {
                return null;
            }
        } else {
            return null;
        }

        HashMap<String,Float> result = new HashMap<>();
        Float rate = 1f;
        Float addMoney = 0f;
        try {
            //log.info("溢价解析开始");
            List<SpPremiumPriceEntity> lst = spPremiumPriceRepository.findByIdPrice(idPrice, 1);
            if (lst != null && lst.size() > 0) {
                for (SpPremiumPriceEntity spPremiumPriceEntity : lst) {
                    result = calSpPremiumPrice(spPremiumPriceEntity, l);
                    if (result != null) {
                        break;
                    }
                }
            } else {
                lst = spPremiumPriceRepository.findByIdFranchisee(param.getIdFranchisee(), 1);
                if (lst != null && lst.size() > 0) {
                    for (SpPremiumPriceEntity spPremiumPriceEntity : lst) {
                        result = calSpPremiumPrice(spPremiumPriceEntity, l);
                        if (result != null) {
                            break;
                        }
                    }
                }
            }

            if (result != null) {
                log.info("溢价结果："+ result.toString());
                if (result.get("addMoney") != null)
                    addMoney = result.get("addMoney").floatValue();
                if (result.get("rate") != null)
                    rate = result.get("rate").floatValue();
            }

            //log.info("溢价解析结束");
        } catch (Exception e) {
            log.info("溢价解析错误："+ e.getMessage());
        }

        float originPrice = basePrice;
        basePrice = basePrice * rate + param.getMarkUpPrice()/100 + addMoney;
        otherPrice = otherPrice * rate;
        money = basePrice + otherPrice;
        priceVO.setTotalPrice(Convert.toFloat(new BigDecimal(money).setScale(2, RoundingMode.HALF_UP).toString()));
        priceVO.setBasePrice(Convert.toFloat(new BigDecimal(basePrice).setScale(2, RoundingMode.HALF_UP).toString()));
        priceVO.setOtherPrice(Convert.toFloat(new BigDecimal(otherPrice).setScale(2, RoundingMode.HALF_UP).toString()));
        priceVO.setAddPrice(basePrice - originPrice);
        log.info("OrderPriceVO: {}", JSON.toJSONString(priceVO));

        return priceVO;
    }

    /**
     * 接送站计算定价
     *
     * @param param
     * @return
     */
    private OrderPriceVO calStationCommonOrderPrice(OrderPoolPriceParam param, boolean isOrder) {
        log.info("calStationCommonOrderPrice OrderPoolPriceParam: {}", JSON.toJSONString(param));
        StationCommonPriceEntity price;
        if (isOrder) {
            price = stationCommonPriceRepository.findByIdStation(param.getIdFranchisee(), param.getIdRailwayStation(),
                    param.getIdServiceType(), param.getIdVehicleType(), param.getChannel());
        } else {
            price = stationCommonPriceRepository.findByIdStationAndStatusOnline(param.getIdFranchisee(), param.getIdRailwayStation(),
                    param.getIdServiceType(), param.getIdVehicleType(), param.getChannel());
        }

        if (price == null)
            return null;

        if (!this.scopeCheck(param, price.getScopeType(), price.getServiceScope(), price.getIdServiceType()))
            return null;

//        String cityCode = null;
//        //区域范围限制
//        if (price.getScopeType() == Constants.ScopeType.ADMINISTRATIVE_AREA) {
//            String loc = param.getOrigins();
//            if (price.getIdServiceType() == Constants.ServiceType.AIRPORT_PICK) {
//                loc = param.getDestinations();
//            }
//            GeoCoderLocationVO originVO = weMapTemplate.geo().location(loc);
//            ResultLocation originLoc = originVO.getResult();
//            //行政区划代码
//            cityCode = originLoc.getAdInfo().getAdcode();
//
//            //String[] scopeCodeArr = price.getServiceScope().split(",");
//            if (!price.getServiceScope().contains(cityCode))
//                return null;
//            //地图围栏限制/围栏内不接单
//        } else if (price.getScopeType() == Constants.ScopeType.MAP_FENCE_IN_AREA) {
//            String scope = price.getServiceScope();
//            if (StringUtil.isNotBlank(scope)) {
//                String[] fenceArr = scope.replace("[", "").replace("]", "").split(",");
//                for (String idFence : fenceArr) {
//                    Integer id = Integer.parseInt(idFence);
//                    boolean res = fenceBiz.addressInFence(id, param.getOrigins(), param.getDestinations());
//                    if (res)
//                        return null;
//                }
//            }
//
//            //地图围栏限制/围栏外不接单
//        } else if (price.getScopeType() == Constants.ScopeType.MAP_FENCE_OUT_AREA) {
//            String scope = price.getServiceScope();
//            if (StringUtil.isNotBlank(scope)) {
//                String[] fenceArr = scope.replace("[", "").replace("]", "").split(",");
//                for (String idFence : fenceArr) {
//                    Integer id = Integer.parseInt(idFence);
//                    boolean res = fenceBiz.addressNotInFence(id, param.getOrigins(), param.getDestinations());
//                    if (!res)
//                        return null;
//                }
//            }
//        }

        try {
            //加价设定和解析
            if (StringUtil.isNotBlank(price.getMarkupPriceSetting())) {
                HashMap<String, Integer> markUpHashMap = this.calMarkUpPrice(param, price.getMarkupPriceSetting(), price.getIdServiceType());
                param.setMarkUpPrice(markUpHashMap.get("price"));
                param.setMarkUpPerPrice(markUpHashMap.get("perPrice"));
            }
        } catch (Exception e) {
            log.info("markUpPrice 出错：{}", JSON.toJSONString(param));
        }

        OrderPriceVO opv = this.findCommonPriceContent(param, price.getPriceContent(), price.getIdServicePriceType());
        //log.info("OrderPriceVO : {}", JSON.toJSONString(opv));
        if (opv == null)
            return null;

        opv.setIdServicePriceType(price.getIdServicePriceType());
        opv.setOrderDistance(param.getOrderDistance());
        opv.setSpendTime(param.getSpendTime());

        return opv;
    }


    /**
     * 接送站计算定价
     *
     * @param param
     * @return
     */
    private OrderPriceVO calNewStationOrderPrice(OrderPoolPriceParam param, boolean isOrder) {

        log.info("OrderPoolPriceParam: {}", JSON.toJSONString(param));
        NewStationPriceEntity price;
        if (isOrder) {
            price = newStationPriceRepository.findByIdStation(param.getIdFranchisee(), param.getIdRailwayStation(),
                    param.getIdServiceType(), param.getIdVehicleType(), param.getChannel());
        } else {
            price = newStationPriceRepository.findByIdStationAndStatusOnline(param.getIdFranchisee(), param.getIdRailwayStation(),
                    param.getIdServiceType(), param.getIdVehicleType(), param.getChannel());
        }

        if (price == null)
            return null;

        if (!this.scopeCheck(param, price.getScopeType(), price.getServiceScope(), price.getIdServiceType()))
            return null;

//        String cityCode = null;
//        //区域范围限制
//        if (price.getScopeType() == Constants.ScopeType.ADMINISTRATIVE_AREA) {
//            String loc = param.getOrigins();
//            if (price.getIdServiceType() == Constants.ServiceType.AIRPORT_PICK) {
//                loc = param.getDestinations();
//            }
//            GeoCoderLocationVO originVO = weMapTemplate.geo().location(loc);
//            ResultLocation originLoc = originVO.getResult();
//            //行政区划代码
//            cityCode = originLoc.getAdInfo().getAdcode();
//
//            //String[] scopeCodeArr = price.getServiceScope().split(",");
//            if (!price.getServiceScope().contains(cityCode))
//                return null;
//            //地图围栏限制/围栏内不接单
//        } else if (price.getScopeType() == Constants.ScopeType.MAP_FENCE_IN_AREA) {
//            String scope = price.getServiceScope();
//            if (StringUtil.isNotBlank(scope)) {
//                String[] fenceArr = scope.replace("[", "").replace("]", "").split(",");
//                for (String idFence : fenceArr) {
//                    Integer id = Integer.parseInt(idFence);
//                    boolean res = fenceBiz.addressInFence(id, param.getOrigins(), param.getDestinations());
//                    if (res)
//                        return null;
//                }
//            }
//
//            //地图围栏限制/围栏外不接单
//        } else if (price.getScopeType() == Constants.ScopeType.MAP_FENCE_OUT_AREA) {
//            String scope = price.getServiceScope();
//            if (StringUtil.isNotBlank(scope)) {
//                String[] fenceArr = scope.replace("[", "").replace("]", "").split(",");
//                for (String idFence : fenceArr) {
//                    Integer id = Integer.parseInt(idFence);
//                    boolean res = fenceBiz.addressNotInFence(id, param.getOrigins(), param.getDestinations());
//                    if (!res)
//                        return null;
//                }
//            }
//        }

        try {
            //加价设定和解析
            if (StringUtil.isNotBlank(price.getMarkupPriceSetting())) {
                HashMap<String, Integer> markUpHashMap = this.calMarkUpPrice(param, price.getMarkupPriceSetting(), price.getIdServiceType());
                param.setMarkUpPrice(markUpHashMap.get("price"));
                param.setMarkUpPerPrice(markUpHashMap.get("perPrice"));
            }

        } catch (Exception e) {
            log.info("markUpPrice 出错：{}", JSON.toJSONString(param));
        }

        log.info("开始计算findPriceContent");
        OrderPriceVO opv = this.findPriceContent(param, price.getPriceContent(), price.getIdServicePriceType());
        if (opv == null)
            return null;

        opv.setIdServicePriceType(price.getIdServicePriceType());
        opv.setOrderDistance(param.getOrderDistance());
        opv.setSpendTime(param.getSpendTime());

        return opv;
    }

    /**
     * 接送机计算定价
     *
     * @param param
     * @return
     */
    private OrderPriceVO calAirportCommonOrderPrice(OrderPoolPriceParam param, boolean isOrder) {
        log.info("calAirportCommonOrderPrice OrderPoolPriceParam : {}", JSON.toJSONString(param));
        AirportCommonPriceEntity price;
        if (isOrder) {
            price = airportCommonPriceRepository.findByIdAirport(param.getIdFranchisee(), param.getIdAirport(),
                    param.getIdServiceType(), param.getIdVehicleType(), param.getChannel());
        } else {
            price = airportCommonPriceRepository.findByIdAirportAndStatusOnline(param.getIdFranchisee(), param.getIdAirport(),
                    param.getIdServiceType(), param.getIdVehicleType(), param.getChannel());
        }

        if (price == null)
            return null;

        if (!this.scopeCheck(param, price.getScopeType(), price.getServiceScope(), price.getIdServiceType()))
            return null;

        try {

            if (StringUtil.isNotBlank(price.getMarkupPriceSetting())) {
                HashMap<String, Integer> markUpHashMap = this.calMarkUpPrice(param, price.getMarkupPriceSetting(), price.getIdServiceType());
                param.setMarkUpPrice(markUpHashMap.get("price"));
                param.setMarkUpPerPrice(markUpHashMap.get("perPrice"));
            }

        } catch (Exception e) {
            log.info("markUpPrice 出错：{}", JSON.toJSONString(param));
        }

        OrderPriceVO opv = this.findCommonPriceContent(param, price.getPriceContent(), price.getIdServicePriceType());
        //log.info("OrderPriceVO : {}", JSON.toJSONString(opv));
        if (opv == null)
            return null;

        opv.setIdServicePriceType(price.getIdServicePriceType());
        opv.setOrderDistance(param.getOrderDistance());
        opv.setSpendTime(param.getSpendTime());

        return opv;
    }

    /**
     * 接送机计算定价
     *
     * @param param
     * @return
     */
    private OrderPriceVO calNewAirportOrderPrice(OrderPoolPriceParam param, boolean isOrder) {
        log.info("calNewAirportOrderPrice OrderPoolPriceParam : {}", JSON.toJSONString(param));
        NewAirportPriceEntity price = null;
        if (!isOrder) {
            price = newAirportPriceRepository.findByIdAirportAndStatusOnLine(param.getIdFranchisee(), param.getIdAirport(),
                    param.getIdServiceType(), param.getIdVehicleType(), param.getChannel());
        } else {
            price = newAirportPriceRepository.findByIdAirport(param.getIdFranchisee(), param.getIdAirport(),
                    param.getIdServiceType(), param.getIdVehicleType(), param.getChannel());
        }

        if (price == null)
            return null;

        if (!this.scopeCheck(param, price.getScopeType(), price.getServiceScope(), price.getIdServiceType()))
            return null;

        try {
            //加价设定和解析
            if (StringUtil.isNotBlank(price.getMarkupPriceSetting())) {
                HashMap<String, Integer> markUpHashMap = this.calMarkUpPrice(param, price.getMarkupPriceSetting(), price.getIdServiceType());
                param.setMarkUpPrice(markUpHashMap.get("price"));
                param.setMarkUpPerPrice(markUpHashMap.get("perPrice"));
            }
        } catch (Exception e) {
            log.info("markUpPrice 出错：{}", JSON.toJSONString(param));
        }

        OrderPriceVO opv = this.findPriceContent(param, price.getPriceContent(), price.getIdServicePriceType());
        //log.info("OrderPriceVO : {}", JSON.toJSONString(opv));
        if (opv == null)
            return null;

        opv.setIdServicePriceType(price.getIdServicePriceType());
        opv.setOrderDistance(param.getOrderDistance());
        opv.setSpendTime(param.getSpendTime());

        log.info("OrderPriceVO: {}", JSON.toJSONString(opv));

        return opv;
    }

    private boolean scopeCheck(OrderPoolPriceParam param, int scopeType, String serviceScope, int idServiceType) {
        String cityCode = null;
        //区域范围限制
        if (scopeType == Constants.ScopeType.ADMINISTRATIVE_AREA) {
            String loc = param.getOrigins();
            if (idServiceType == Constants.ServiceType.AIRPORT_PICK) {
                loc = param.getDestinations();
            }
            GeoCoderLocationVO originVO = weMapTemplate.geo().location(loc);
            ResultLocation originLoc = originVO.getResult();
            //行政区划代码
            cityCode = originLoc.getAdInfo().getAdcode();

            if (!serviceScope.contains(cityCode))
                return false;
            //地图围栏限制/围栏内不接单
        } else if (scopeType == Constants.ScopeType.MAP_FENCE_IN_AREA) {
            if (StringUtil.isNotBlank(serviceScope)) {
                String[] fenceArr = serviceScope.replace("[", "").replace("]", "").split(",");
                for (String idFence : fenceArr) {
                    Integer id = Integer.parseInt(idFence);
                    boolean res = fenceBiz.addressInFence(id, param.getOrigins(), param.getDestinations());
                    if (res)
                        return false;
                }
            }
            //地图围栏限制/围栏外不接单
        } else if (scopeType == Constants.ScopeType.MAP_FENCE_OUT_AREA) {
            if (StringUtil.isNotBlank(serviceScope)) {
                String[] fenceArr = serviceScope.replace("[", "").replace("]", "").split(",");
                for (String idFence : fenceArr) {
                    Integer id = Integer.parseInt(idFence);
                    boolean res = fenceBiz.addressNotInFence(id, param.getOrigins(), param.getDestinations());
                    if (!res)
                        return false;
                }
            }
        }
        return true;
    }

    private HashMap calMarkUpPrice(OrderPoolPriceParam param, String markUpPriceStr, int idServiceType) {
        HashMap<String, Integer> result = new HashMap<>();
        //加价设定和解析
        if (StringUtil.isNotBlank(markUpPriceStr)) {
            String loc = param.getOrigins();
            if (idServiceType == Constants.ServiceType.AIRPORT_PICK)
                loc = param.getDestinations();

            JSONArray array = JSONArray.parseArray(markUpPriceStr);
            List<MarkUpPrice> lst = JSON.parseArray(array.toString(), MarkUpPrice.class);
            for (int i = 0; i < lst.size(); i++) {
                MarkUpPrice markUpPrice = lst.get(i);
                if (markUpPrice.getType() == Constants.ScopeType.ADMINISTRATIVE_AREA) {
                    GeoCoderLocationVO originVO = weMapTemplate.geo().location(loc);
                    ResultLocation originLoc = originVO.getResult();
                    //行政区划代码
                    String cityCode = originLoc.getAdInfo().getAdcode();
                    if (markUpPrice.getId().contains(cityCode)) {
                        result.put("price", markUpPrice.getPrice());
                        result.put("perPrice", markUpPrice.getPre_price());
                        return result;
                    }
                } else if (markUpPrice.getType() == Constants.ScopeType.MAP_FENCE_IN_AREA) {
                    if (StringUtil.isNotBlank(markUpPrice.getId())) {
                        String[] idx = markUpPrice.getId().split(",");
                        String[] points = loc.split(",");
                        for (String idFence : idx) {
                            boolean res = fenceBiz.isInFence(Integer.parseInt(idFence), points[0], points[1]);
                            if (res) {
                                result.put("price", markUpPrice.getPrice());
                                result.put("perPrice", markUpPrice.getPre_price());
                                return result;
                            }
                        }
                    }
                }
            }
        }

        result.put("price", 0);
        result.put("perPrice", 0);
        return result;
    }

    private HashMap calSpPremiumPrice(SpPremiumPriceEntity spPremiumPriceEntity, LocalDateTime appointmentTime) {
        HashMap<String,Float> price = new HashMap<>();

        log.info("calSpPremiumPrice :{}", JSON.toJSONString(spPremiumPriceEntity));
        int appointTime = appointmentTime.getHour() * 100 + appointmentTime.getMinute();
        log.info("appointTime :{}" + appointTime);

        Float rate = 1f;
        Float addMoney = 0f;
        float addRate = 0f;
        //log.info("SpPremiumPriceEntity :{}", JSON.toJSONString(spPremiumPriceEntity));
        if (StringUtil.isNotBlank(spPremiumPriceEntity.getPremiumStartDate()) &&
                StringUtil.isNotBlank(spPremiumPriceEntity.getPremiumEndDate())) {
            //日期
            LocalDateTime startDay = DateUtil.parseLocalDayTime(spPremiumPriceEntity.getPremiumStartDate());
            LocalDateTime endDay = DateUtil.parseLocalDayTime(spPremiumPriceEntity.getPremiumEndDate());
            if (startDay.isBefore(appointmentTime) && endDay.isAfter(appointmentTime)) {
                if (spPremiumPriceEntity.getPrice() != null) {
                    addMoney = (float) (spPremiumPriceEntity.getPrice() / 100);
                }
                if (addMoney <= 0) {
                    if (spPremiumPriceEntity.getRate() != null) {
                        addRate = (float) (spPremiumPriceEntity.getRate() / 100);
                        rate = rate + addRate;
                    }
                }
                price.put("rate",rate);
                price.put("addMoney",addMoney);
                return price;
            }
        } else {
            String[] timeArr = spPremiumPriceEntity.getPremiumTime().replace(":","").replace(".","").split("-");
            int startTime = Integer.valueOf(timeArr[0]);
            int endTime = Integer.valueOf(timeArr[1]);
            boolean isFind = false;
            if (endTime >= startTime) {
                if (appointTime >= startTime && appointTime <= endTime) {
                    isFind = true;
                }
            } else {
                if ((appointTime >= startTime && appointTime <= 2400) || (appointTime <= endTime)) {
                    isFind = true;
                }
            }

            if (isFind) {
                if (spPremiumPriceEntity.getPrice() != null) {
                    addMoney = (float) (spPremiumPriceEntity.getPrice() / 100);
                }
                if (addMoney <= 0) {
                    if (spPremiumPriceEntity.getRate() != null)
                        addRate = (float) (spPremiumPriceEntity.getRate() / 100);
                        rate = rate + addRate;
                }
                price.put("rate", rate);
                price.put("addMoney", addMoney);
                return price;
            }
        }

        return null;
    }

    private AirportEntity getAirport1(String cityCode,String name,String name2) {
        List<AirportEntity> list = airportRepository.findByAirPortName1(cityCode,name,name2);
        if (list.size()>0){
            return list.get(0);
        } else {
            return null;
            //throw new BusinessException(5002,"未找到对应的机场");
        }
    }

    private AirportEntity getAirport2(String cityCode, String name) {
        List<AirportEntity> list = airportRepository.findByAirPortName2(cityCode, name);
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
            //throw new BusinessException(5002,"未找到对应的机场");
        }
    }

    private RailwayEntity getRailwayStation(String cityCode, String name) {
        List<RailwayEntity> list = railStationRepository.findByRailwayName(cityCode, name);
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
            //throw new BusinessException(5002,"未找到对应的火车站");
        }
    }

    /**
     * 条件检索查询
     * @param param
     * @return
     */
    @Override
    public PagingResultVO<OrderPoolVO> orderSearch(SpListParam param, Boolean forHistory) {
        String idFranchiseeArr = franchiseeBiz.findIdFranArrByDispacther(param.getIdDispatcher());
        if (StringUtil.isNotBlank(idFranchiseeArr)) {
            param.setIdFranchiseeArr(idFranchiseeArr);
            param.setIdFranchisee(null);
        } else {
            idFranchiseeArr = franchiseeBiz.findIdFranArrByFinance(param.getIdDispatcher());
            if (StringUtil.isNotBlank(idFranchiseeArr)) {
                param.setIdFranchiseeArr(idFranchiseeArr);
                param.setIdFranchisee(null);
            }
        }

        List<OrderPoolVO> list = orderMapper.searchWithConditionsAndPaging(param);
        for (OrderPoolVO orderPoolVO :list) {
            orderPoolVO.setCity(HashMapConstants.idFranchiseeCityMap.get(orderPoolVO.getIdFranchisee()));
        }
        return new PagingResultVO(orderMapper.searchWithConditionsAndPagingTotal(param), list);
    }

}
